texts: Is it a good idea to have a public inner class as a runner for a service?

texts:
I have a service class that handles recipe management using a piquetteClient (piquette is a web app with a rest API that can run puppet scripts).

The thing is this service class has a bunch of methods like runRecipe, searchRecipes, filter, list etc, and they all require a piquetteClient instance. Because I wanted to not be able to run any of this methods without having first a valid instance of piquetteClient and because I don't want to have it as a parameter for each method (and don't also I don't like to have it externally with a setter because then you give the user the option to just not call that setter - it's confusing), I create a public inner class Runner inside this service and buildRunner method outside the inner class that can give you an instance of the runner only after you provide a valid piquette client instance, after that, the same instance will be used everywhere.

What do you think?

@Component
public class RecipeServiceImpl implements RecipeService {

    private static final long serialVersionUID = 1000050450505050443L;

    @Override
    public Runner buildInternalRunner(PiquetteClient piquetteClient) {
        // validate client instance
        Runner runner = new Runner(piquetteClient);
        return runner;
    }

    public class Runner {

        private final PiquetteClient piquetteClient;

        Runner(PiquetteClient piquetteClient) {
            this.piquetteClient = piquetteClient;
        }

        public List<Recipe> searchRecipes(String query, int limit, int offet) {
            return filterRecipes(piquetteClient.recipes(query, Integer.MAX_VALUE, 0), query, limit);
        }

        /**
         *
         * @param recipeName
         * @param asset
         * @return Future of Integers
         */
        @Async
        public Future<Integer> runRecipe(String recipeName, String asset) {
            // trying to get the correct asset
            String regexAsset = RegexUtil.ANY_CHAR + asset + RegexUtil.ANY_CHAR;
            List<Artifact> artifacts = listArtifacts(recipeName, regexAsset);
            if (!artifacts.isEmpty()) {
                if (artifacts.size() > 1) {
                    log.warn("Multiple artifacts matched... choosing the first one: " + artifacts.get(0).getBuild());
                }
                URI uri = artifacts.get(0).getBuild();
                log.info("Running: " + artifacts.get(0).getBuild());
                return new AsyncResult<>(piquetteClient.runRecipe(recipeName, uri).getId());
            } else {
                log.error("Nothing for: " + recipeName + " and asset: " + regexAsset);
            }
            return new AsyncResult<>(NumberUtils.INTEGER_ZERO);
        }

        // other similar methods
}

RecipeService interface:

public interface RecipeService extends Serializable {
     RecipeServiceImpl.Runner buildInternalRunner(PiquetteClient piquetteClient);
}

I can't use the constructor because RecipeServiceImpl is a Spring component. The build method it's an override because it's declared in the Service interface so I can inject the service everywhere and use the method. Maybe the name Runner is a bad one, but I was asking how this concept feels like; you have a service implementation that has another object inside that does the actual job. The service itself is just validating and delegating... From outside you can't have a reference to the runner object without having first an instance of the service itself and provide to this instance the necessary data.


texts:
I'm currently creating a 2d game in python. I have to calculate the closest enemy so the player knows which one to target. I have the following function to accomplish this task:

import math

def find_closest(character: tuple, enemies: list) -> (int, int):
    """
    Finds the closest enemy in enemies

    :param character: An (x, y) representing the position of the character\n
    :param enemies: A list of tuples (x, y) that represent enemies

    :return: A tuple (x, y) of the closest enemy
    """
    closest_enemy = None
    smallest_distance = 100_000_000 # Set to large number to ensure values can be less #
    for enemy in enemies:
        distance = math.sqrt(math.pow(character[0] - enemy[0], 2) + (math.pow(character[1] - enemy[1], 2)))
        if distance < smallest_distance:
            closest_enemy = (enemy[0], enemy[1])
            smallest_distance = distance
    return closest_enemy

if __name__ == "__main__":

    # Test Case #

    character = (5, 6)
    enemies = [(1, 2), (3, 4), (7, 6), (11, 4)]
    closest = find_closest(character, enemies)
    print(closest)

I would like to know if there's any better way to go about doing this. While it is a simple function, I'm sure there's some built in python function that can accomplish this even shorter. I use tuples because, in my opinion, they're the best way to represent coordinates. Any and all suggestions and/or improvements are welcome and appreciated.


texts: Haskell: Draw tabulated data given header and rows as lists

texts:
I need to draw tabulated data given a header as list and rows as list of lists
This is what I came up with. I wouldn't say that I like it much.
Could you please have a look if it can be done better (I am sure it can) and generally point to any error and possible optimization. Maybe someone has done exact same thing before. Thanks.

import Data.Text (justifyLeft, unpack, pack)
import Data.Char (toUpper)

tDraw :: [String] -> [[String]] -> IO()
tDraw h rs = do
  putChar '\n'
  -- draw header
  mapM_ (\x -> putStr x) header
  putChar '\n'
  -- draw separator line
  mapM_ (\x -> putChar x) (replicate (cell * length header) '=')
  putChar '\n'
  -- draw rows
  mapM_ (\x -> row cell x) rs
  where
    cell = if l < 10 then 12 else l + 2
           where l = (maximum . map (\x -> length x) . concat) (h:rs)
    header = map (\x -> strToUp $ unpack $ justifyLeft cell ' ' (pack x)) h
             where strToUp = map (\c -> toUpper c)
    row n l  = do
      mapM_ (\x -> putStr $ unpack $ justifyLeft n ' ' (pack x)) l
      putChar '\n'


texts:
I have some code that I wrote almost a year ago exactly (1/9/2013) and I would like to know if I wrote it well or if it can be improved.  I don't have any fun input or output, as these are not set results coming out of this column in the table.

-- =============================================
-- Author: Malachi (Name Changed to Protect the possibly Guilty)
-- Create date: 1/9/2013
-- Description: Will give a list of the Bond Conditions
-- =============================================
CREATE FUNCTION [dbo].[fnBondConditionList]
(
    @BondID int
)
RETURNS Varchar(MAX)
AS
BEGIN
    DECLARE @Result Varchar(MAX)

    SELECT @Result = (Select Justice.dbo.uCode.Description as BondConditions
        FROM Justice.dbo.uCode INNER JOIN
            Justice.dbo.xBondCondition ON Justice.dbo.uCode.CodeID = Justice.dbo.xBondCondition.ConditionID
        WHERE Justice.dbo.xBondCondition.BondID = @BondID
        FOR XML PATH (''))

    SET @Result = replace(@Result, '<BondConditions>','')
    SET @Result = replace(@Result, '</BondConditions>','<br />')
    Set @Result = LEFT(@Result, LEN(@Result) - 1)

RETURN @Result
END

I cannot change the tables.  Here are the table layouts:

uCode:

CREATE TABLE [dbo].[uCode](
    [CodeID] [dbo].[CodeID] NOT NULL,
    [CacheTableID] [dbo].[CacheTableID] NOT NULL,
    [RevisionID] [dbo].[RevisionID] NOT NULL,
    [Code] [dbo].[Word] NOT NULL,
    [RootNodeID] [dbo].[NodeID] NOT NULL,
    [EffectiveDate] [datetime] NULL,
    [ObsoleteDate] [dbo].[ObsoleteDate] NULL,
    [UserIDCreate] [dbo].[UserIDCreate] NOT NULL,
    [TimestampCreate] [dbo].[TimestampCreate] NOT NULL,
    [UserIDChange] [dbo].[UserIDChange] NULL,
    [TimestampChange] [dbo].[TimestampChange] NULL,
    [FilterState] [dbo].[StateCode] NULL,
    [FilterSiteID] [dbo].[GUID] NULL,
    [Description] [dbo].[DescriptionLong] NULL,
CONSTRAINT [PK_uCode] PRIMARY KEY NONCLUSTERED
(
    [CodeID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
CONSTRAINT [IXuCode1] UNIQUE CLUSTERED
(
    [CacheTableID] ASC,
    [CodeID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

xBondCondition:

CREATE TABLE [dbo].[xBondCondition](
    [BondID] [dbo].[BondID] NOT NULL,
    [ConditionID] [dbo].[CodeID] NOT NULL,
CONSTRAINT [PK_xBonduCode] PRIMARY KEY CLUSTERED
(
    [BondID] ASC,
    [ConditionID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

This code was created to stuff everything from one column into a single column of a single record, which is then fed to a stored procedure that fills a datagrid.

Should I be looping this somehow (I get a bad taste in my mouth just typing that)?

I update this because I find myself using the same FOR XML PATH ('') Template for something very similar.

I cannot use CONCAT because I am using SQL SERVER 2008 (wouldn't that be nice).

With all that going into the Stored Procedure, the SPROC Renders something similar to this:

Where the rightmost column is the column of the SPROC that was produced by a function almost exactly the same as above.


texts:
I'm not even sure if this is how you're supposed to do it, but this is what I have so far:

$.getJSON("/api/get_categories", function(data){
    var items = [];
   $.each(data["categories"], function(key, value){

    items.push('
<div class="card waves-effect waves-block waves-light"

'+value+'

');
   });

   $("#categories").html(items.join(""));

});

The issue is that the string within my push looks really awkward and long. What's the better way of doing this?


texts:
I have a small 10-liner function that writes some data to a file using an std::ofstream. I did not explicitly call .close() at the end of my function, but it failed code review with the reason that it is better to explicitly call it for style and verbosity reasons. I understand there is no harm in calling .close() explicitly, but does calling it explicitly just before a return statement indicate a lack of understanding or faith in RAII?

The C++ standard says:

  §27.8.1.2

  virtual ~ basic_filebuf ();

  [3] Effects: Destroys an object of class basic_filebuf<charT,traits>. Calls close().

Am I justified in my argument that calling .close() at the end of a function is redundant and/or unnecessary?

bool SomeClass::saveData()
{
    std::ofstream saveFile(m_filename);

    if (!saveFile.is_open())
        return false;

    saveFile << m_member1 << std::endl;
    saveFile << m_member2 << std::endl;

    saveFile.close(); // passed review only with this line
    return true;
}

The function is only supposed to return false if the file could not be opened for writing.


texts:
Challenge

  An integer is provided as an input. In each step, we have to subtract
  a number from the input which already exists as a digit of the input.
  In this way, we have to make the input equal to zero(0). The problem
  is to output the minimum number of such steps.

Code

n=int(input())
count=0

while n:
    l=list(int(i) for i in str(n))
    n=n-max(l)
    count+=1
    if n == 0:
        break

print (count)

The code outputs the correct results; but on larger input it exceeds the time limits.
That is, for every input memory consumption increases and the time limit is reached up until the 30th test case.


texts: Check if any of the coordinates are within a certain distance using apply in Python pandas with two data frames

texts:
I wrote this code that takes the vessel coordinates and checks them against every possible port coordinates. If the distance between the vessel and the port coordinates is within x meters (in this example, it has to be less than 3 km), then add that port and the distance_to_the_port to the data frame.
Example dataframes:
df_ports = pd.DataFrame({'Ports':['Port_A','Port_B','Port_C'], 'latitude': [1,5,3], 'longitude':[1,10,5]})
latitude_and_longitude_columns = df_ports.iloc[:, [1,2]]
df_ports['coordinates_tuple'] = latitude_and_longitude_columns.apply(tuple, axis=1)

df_vessel = pd.DataFrame({'latitude': [1,5,7], 'longitude':[1,10,20]})
latitude_and_longitude_columns = df_vessel.iloc[:, [0,1]]
df_vessel['coordinates_tuple'] = latitude_and_longitude_columns.apply(tuple, axis=1)

df_vessel['distance_to_port_in_meters'] = -1
df_vessel['port'] = -1

The function that checks the distance:
def get_distance_between_two_points(tuple1, tuple2):
    from geopy import distance
    radius = 3000
    dist = distance.distance(tuple1, tuple2).m
    if dist < radius:
        return dist
    return -1

The logic:
for _, port_row in df_ports.iterrows():

        port = port_row['Ports']
        result = df_vessel.apply(lambda vessel_row : get_distance_between_two_points(vessel_row['coordinates_tuple'], port_row['coordinates_tuple']), axis=1)

        for index, value in result[result != -1].items():
            df_vessel.loc[index, 'distance_to_port_in_meters'] = int(value)
            df_vessel.loc[index, 'port'] = port

Result:
 latitude  longitude coordinates_tuple  distance_to_port_in_meters    port
0         1          1            (1, 1)                           0  Port_A
1         5         10           (5, 10)                           0  Port_B
2         7         20           (7, 20)                          -1      -1

The result is correct and it works with my bigger data sample.
How can I improve this?
In my current code, I have 4800 vessel coordinates and 137 ports. It takes just above 2 minutes to go through the code. How can I make my code better and possibly faster?


texts:
Write a pointer version of the function strcat that we showed in Chapter 2: strcat(s, t) copies the string t to the end of s.

This is the version of strcat from Chapter 2:

void strcat(char s[], char t[]) {
    int i, j;

    i = j = 0;
    while(s[i] != '\0') /* find the end of s */
        i++;

    while((s[i++] = t[j++]) != '\0') /*  copy t */
        ;
}

Here is my solution:

void custom_strcat(char *s, char *t) {
    while(*s) /* finding the end of the string */
        s++;

    while((*s++ = *t++)) /* copy t */
        ;
}

There are 2 while loops in my function, first loop will run until *s is equal to '\0'. At each iteration the value of s is incremented - thus, it will point to the next element;

The second loop will copy the elements of the string t at the and of s. The incrementation is done in the test part - even though after the loop stops s and t will point to other objects.This technique couldn't be applied in the first loop because when the loop stops s will point to an irrelevant value.

The exercise can be found at page 121 in K&R second edition.


texts: Program in JAVA to generate random alphanumeric string

texts:
This code will generate a pseudorandom alphanumeric string of given length.
I would welcome suggestions on how to make it more random. Beyond that, have I made any convention violations, Exception cases, and the like?
Also, is there any way to make it faster?

public class Test
{
    public static String getRandomAlphaNum(int length)
    {
        String charstring = "abcdefghijklmnopqrstuvwxyz0123456789";
        String randalphanum = "";
        double randroll;
        char randchar;
        for
        (double i = 0; i < length; i++)
        {
            randroll = Math.random();
            randchar = '@';
            for
            (int j = 1; j <= 36; j++)
            {
                if
                (randroll <= (1.0 / 36.0 * j))
                {
                    randchar = charstring.charAt(j - 1);
                    break;
                }
            }
            randalphanum += randchar;
        }
        return randalphanum;
    }
}


texts: Splitting a div and positioning an inner div

texts:
I have an outer div with...

Width
Number of slots the outer div represents

The intent is to add a child div, but position the child div based on the start and end slot in the parent div.

To achieve this behavior, I am calculating the width per slot and the width of child div, plus the margin left of child div.

import React from 'react';

let parentDivStyle = {
    border: '1px solid black',
    height: '50px',
    align: 'center',
    display: 'inline-block'
}

let childDivStyle = {
    backgroundColor: 'darkseagreen',
    marginTop: '5px',
    height: '40px',
}

const DivColoring = (props) => {
    let parentDivWith = props.parentDivWidth;
    let totalSlots = props.totalSlots;
    let startSlot = props.startSlot;
    let endSlot = props.endSlot;

    let widthPerSlot = Math.round(parentDivWith / totalSlots);

    console.log('widthPerSlot= ', widthPerSlot);
    let childWidth = parentDivWith;

    let marginLeft = 0;

    //if startSlot is greater than 1, calculate the Left Margin and Width.
    if (startSlot > 1) {
        marginLeft = (startSlot - 1) * widthPerSlot;
    }

    //if end is present and is less than totalSlots update childWidth

    if (endSlot && endSlot <= totalSlots) {
        childWidth = widthPerSlot * (endSlot - startSlot + 1);
    }

    //add 1 px to marginLeft of child div
    marginLeft = marginLeft + 1;
    //remove 2 px from childWidth to add a padding of 1px at end
    childWidth = childWidth - 2;

    return (

);
}

export default DivColoring;

Please see the working example here https://stackblitz.com/edit/react-be8wxg

Is there any better of achieving this behavior. Thanks.


texts: Is there any performance increase converting search term to lower case before LINQ

texts:
Please have a look at the following 2 snippets:

var query = _ctx.Notes.Where(...);
var searchLower = searchTerms.ToLower();
query = query.Where(a => a.Comment.ToLower().Contains(searchLower))

vs

var query = _ctx.Notes.Where(...);
query = query.Where(a => a.Comment.ToLower().Contains(searchTerms.ToLower()))

Is there any peformance increase by converting the search terms before carrying out the LINQ query?


texts:
I am trying to find non bouncy numbers under \$10^x\$ where \$1\le x\le 1000\$.
\$123456\$ is an increasing number where every digit is greater than or equal to the previous digit (\$1223344\$ is also counted as an increasing number).
Similarly a decreasing number is one where every digit is smaller than or equal to the previous digit (\$443322\$ is also counted as an decreasing number).

155224 such numbers, which are neither increasing, nor decreasing, are bouncy numbers, such that 12951 numbers below one-million that are not bouncy. I want to find number of non bouncy number under \$10^x\$.

My code works perfectly fine, but when \$n\$ is greater than 7, it takes way too much time to give the output! So, it needs performance optimizations.

import java.util.*;
class A{
static String s;
public static void main(String z[]){
    int n,i;
    Scanner sc=new Scanner(System.in);
    n=sc.nextInt();
    int input[]=new int[n];
    int output[]=new int[n];
    for(i=0;i<n;i++){
        input[i]=sc.nextInt();
    }
    for(i=0;i<n;i++){
        output[i]=noOfBouncy(input[i]);
    }
    for(i=0;i<n;i++){
        System.out.println(output[i]);
    }
}
public static boolean isIncreasing(String s){
     int len=s.length();
     for(int i=0;i<len-1;i++){
         if(s.charAt(i)>s.charAt(i+1)){
             return false;
         }
    }
return true;
}
public static boolean isDecreasing(String s){
     int len=s.length();
     for(int i=0;i<len-1;i++){
         if(s.charAt(i)<s.charAt(i+1)){
             return false;
         }
    }
return true;
}
public static int noOfBouncy(int k){
int limit=(int)Math.pow(10,k);
int count=0;
int num=1;
while(num<limit){
    s=new String(Integer.toString(num));
    if(isIncreasing(s) || isDecreasing(s) ){
    }
    else{
       count++;
    }
    num++;
  }
count=limit-count;
return count-1;
}
}


texts: Improving a function from using 1-D arrays to 2-D arrays as argument

texts:
The problem:

I have a function that writes an array it takes as argument to a div, in a single line.

Example:
writeToOutput([1,2,3]) outputs
    1,2,3

The aim is to improve this function, to be able to take an array of arguments, and display them on several lines

Example: writeToOutput([[1,2,3],[4,5,6]]) outputs

1,2,3
4,5,6

An obvious solution is to use writeToOutput([[1,2,3]]) to replicate the previous results, however, the function call with a 1-D array is already used by several scripts, and I would like them to keep working.

The code:

function writeToOutput(values, outputName) {
  var outputDiv = document.getElementById(outputName)
  var outputText = "";

  if (!Array.isArray(values[0])) {
    values = [values]
  }

  var valuesSubArray;
  for (var i = 0; i < values.length; i++) {
    valuesSubArray = values[i];
    outputText = "";
    for (var j = 0; j < valuesSubArray.length; j++) {
      outputText += valuesSubArray[j]
    }
    if (i > 0) {
      outputDiv.innerHTML += "</br>";
    }
    outputDiv.innerHTML += outputText;
  }
}

What I am interested in:

As you may have guessed, I don't really care about writing numbers to a div, but I have a legacy function that takes a 1-D array, and I would like it to deal with 2-D arrays without breaking existing implementation.

I am interesting in figuring out if the trick with Array.isArray(values[0]) is the best way to do this, or if there is more performant, more widely used, etc. ways to do this. (The project is using jQuery).

Altought this stub has been made to sugarcoat the 1-D -> 2-D array, I am eager to learn, and if there is an obvious improvement to be made, please let me know!


texts:
So I have the following code that takes the input of two arrays, and apply some queries to match elements from DBpediaClassesArray with elements from YagoClassesArray, then it returns the number of elements that are similar in the two ArrayLists.
    public static void get_ND_Matches() throws IOException{
    @SuppressWarnings("rawtypes")
    List<String> DBpediaClassesArray = new ArrayList<String>();
    List<String> YagoClassesArray = new ArrayList<String>();
    DBpediaClassesArray = new ArrayList<String>( ClassesRetrieval.getDBpediaClasses());
    YagoClassesArray = new ArrayList<String>( ClassesRetrieval.fileToArrayListYago());
    String YagoClassWithMaxMatches="";
    HashMap<String,Integer> mappingYagoLabelMaxValue = new HashMap<String,Integer>();
    int NumberOfCommonInstances;
    HashMap<String,ArrayList<String>> MappingYagoClassWithInstances = new HashMap<>();

    for(String yagoClass:YagoClassesArray){
        MappingYagoClassWithInstances.put(yagoClass, GetYagooClassInstances(yagoClass));
        System.out.println("Done for : "+yagoClass );
    }
    for(String dbClass:DBpediaClassesArray){
        ArrayList<String> DBpediaInstancesArray = GetDBpediaClassInstances(dbClass);
        for(Map.Entry<String, ArrayList<String>> YagoMapEntry : MappingYagoClassWithInstances.entrySet()){
            String yagoClass=YagoMapEntry.getKey();
            Set<String> IntersectionSet =Sets.intersection(Sets.newHashSet(DBpediaInstancesArray), Sets.newHashSet(YagoMapEntry.getValue()));
            //System.out.println(dbClass + " and "+ yagoClass+ " = "+ IntersectionSet.size());
            NumberOfCommonInstances = IntersectionSet.size();
            mappingYagoLabelMaxValue.put(yagoClass, NumberOfCommonInstances);
        }
        int MaximumValueOfIntersection=(Collections.max(mappingYagoLabelMaxValue.values()));
        for(Entry<String, Integer> YagoLabelToValueEntry:mappingYagoLabelMaxValue.entrySet()){
            if(YagoLabelToValueEntry.getValue()==MaximumValueOfIntersection && MaximumValueOfIntersection != 0){
                 YagoClassWithMaxMatches = YagoLabelToValueEntry.getKey();
            }
            if(MaximumValueOfIntersection==0){
                YagoClassWithMaxMatches = "Nothing in yago";
            }
        }
        System.out.println("-------------------------------");
        System.out.println(dbClass+" Corresponds to "+ YagoClassWithMaxMatches+" with : "+MaximumValueOfIntersection);
        System.out.println("-------------------------------");

    }
}

This code returns for example:

Actor from DBPEDIA Corresponds to Yago_Actor
Album from DBPEDIA Corresponds to Yago_Album
SomeClass from DBPEDIA Corresponds to nothing in Yago

Etc..
Behind the scenes, this code uses getDBpediaClasses and then applies GetDBpediaClassInstances method to get an ArrayList of results for each class. Each ArrayList resulted is then compared to another ArrayList generated by GetYagooClassInstances for each class of fileToArrayListYago().
Now, because of all the calculations made in the background (there are millions of elements in each array), this process takes hours to execute, because it runs each comparison after another, while it would be better to get them all done at once and then just get the YagoClassWithMaxMatches after all of them have been computed.
I was thinking of concurrency, but I first wanted to see if there is an easier way.
Are there any suggestions to make the code run faster?


texts: Winforms tools for selection of items using ComboBox - binding datasource

texts:
This is mi UserControl containing ComboBox and few buttons for selecting and manipulating collection of items which implement simple interface IHasHeader (just header with name and ID).

It works now but I feel that I use some not ideal hacks, especially in the area of binding of ComboBox's datasource. I'll be glad for any review notes.

public partial class TemplateSelector : UserControl
{
    /// <summary>
    /// Type of access right
    /// </summary>
    public enum TemplateType
    {
        Private,
        Public
    }

    private BindingSource bindSrc = new BindingSource();
    private IHasHeader SelectedItem;
    private bool doHandleSelection = true;

    // delegates

    public delegate void ItemSelectedHandler(IHasHeader item);
    public delegate void NewTemplateSelectionHandler(string name, bool isPublic);
    public delegate void NameSelectionHandler(string name);

    // events

    public event ItemSelectedHandler TemplateSelectionChanged = delegate { };
    public event NameSelectionHandler TemplateDeleting = delegate { };
    public event NewTemplateSelectionHandler CreatingNewTemplate = delegate { };
    public event Action RefreshingTemplatesList = delegate { };
    public event Action ClearingTemplate = delegate { };

    public TemplateType SelectedTemplateType { get; set; }

    public IEnumerable<IHasHeader> TemplatesDatasource
    {
        set
        {
            doHandleSelection = false;
            bindSrc.DataSource = value;
            cboxTemplates.DataSource = bindSrc;
            cboxTemplates.SelectedIndex = -1;
            doHandleSelection = true;
        }
    }

    public TemplateSelector()
    {
        InitializeComponent();
        cboxTemplates.SelectedIndexChanged += cboxTemplates_SelectedIndexChanged;
    }

    /// <summary>
    /// Select given item
    /// </summary>
    /// <param name="item"></param>
    public void SelectItem(IHasHeader item)
    {
        for (int i = 0; i < cboxTemplates.Items.Count; ++i)
        {
            if ((cboxTemplates.Items[i] as IHasHeader).Header.ID == item.Header.ID)
            {
                SelectedItem = item;
                cboxTemplates.SelectedIndex = i;
                return;
            }
        }
    }

    /// <summary>
    /// Clear selection of combobox
    /// </summary>
    public void ClearSelection()
    {
        cboxTemplates.SelectedIndex = -1;
        SelectedItem = null;
    }

    /// <summary>
    /// Add item to combobox datasource
    /// </summary>
    /// <param name="item"></param>
    public void AddItem(IHasHeader item)
    {
        var newSource = (bindSrc.DataSource as IEnumerable<IHasHeader>).ToList();
        newSource.Add(item);
        TemplatesDatasource = newSource;
    }

    private void btnDelete_Click(object sender, EventArgs e)
    {
        if (cboxTemplates.SelectedItem is IHasHeader)
        {
            IHasHeader selected = cboxTemplates.SelectedItem as IHasHeader;
            TemplateDeleting(selected.Header.Name);
            bindSrc.ResetBindings(false);
        }
        ClearSelection();
        ClearingTemplate();
    }

    private void btnNew_Click(object sender, EventArgs e)
    {
        CreatingNewTemplate(TextBoxNewTemplateNew.Text, RadioButtonMeasureQuantitySaveSettingsPublic.Checked);
        bindSrc.ResetBindings(false);
    }

    private void cboxTemplates_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (cboxTemplates.SelectedItem is IHasHeader && doHandleSelection)
        {
            IHasHeader selected = cboxTemplates.SelectedItem as IHasHeader;
            TemplateSelectionChanged(selected);
        }
    }

    private void btnRefresh_Click(object sender, EventArgs e)
    {
        RefreshingTemplatesList();
        bindSrc.ResetBindings(false);
        cboxTemplates.SelectedItem = SelectedItem;
    }

    private void btnClear_Click(object sender, EventArgs e)
    {
        ClearSelection();
        ClearingTemplate();
    }
}


texts: Scheduling Algorithm : First Come First Serve

texts:
I am practicing opearator overloading and to write copy constructor. I have written this program of scheduling algoritrhm. Please suggest me some improvements.

#include <iostream>
#include <vector>

class Scheduling
{
    int process;
    std::vector<int> burst_time;
    std::vector<int> waiting_time;

  public:
    Scheduling() : process(0) {}
    Scheduling(int n) : process(n)
    {
        for (int i = 0; i < n; i++)
        {
            std::cout << "Enter Burst time for process " << i+1 << " : ";
            int val;
            std::cin >> val;
            burst_time.push_back(val);
        }
    }

    //copy constructor
    Scheduling(const Scheduling &other)
    {
        process = other.process;
        int size = other.burst_time.size();

        for (int i = 0; i < size; i++)
        {
            burst_time.push_back(other.burst_time[i]);
        }
    }

    //copy assignment
    Scheduling &operator=(const Scheduling &other)
    {
        process = other.process;
        int size = other.burst_time.size();

        for (int i = 0; i < size; i++)
        {
            burst_time.push_back(other.burst_time[i]);
        }

        return *this;
    }

    std::vector<int> cal_waiting_time(std::vector<int>& burst_time)
    {
        waiting_time.push_back(0);

        for (int i = 0; i < burst_time.size() - 1; i++)
        {
            waiting_time.push_back(waiting_time[i] + burst_time[i]);
        }
        return waiting_time;
    }

    void print_table()
    {
        waiting_time = cal_waiting_time(burst_time);
        std::cout << "Process\t Burst Time\t Waiting Time\n";
        for (int i = 0; i < burst_time.size(); i++)
        {
            std::cout << i+1 << "\t\t " << burst_time[i] << "\t\t " << waiting_time[i] << "\n";
        }
    }
};

int main()
{
    int num;
    std::cout << "Enter number of process\n";
    std::cin >> num;
    Scheduling batch1(num);
    batch1.print_table();

    Scheduling batch2(batch1);
    batch2.print_table();
}


texts: Generic implementation of the Quick-Union algorithm with Path Compression

texts:
Working my way through Algorithms, Fourth edition by Robert Sedgewick & Kevin Wayne. I implemented a generic version of the Quick-Union algorithm and added Path Compression (not described in the book) to it.

Mainly I'm looking for feedback on these two aspects and whether I might have overlooked a side effect.

public class WeightedQuickUnionWithPathCompression<T> {
    private final Map<T, T> components = new HashMap<>();
    private final Map<T, Integer> treeSizes = new HashMap<>();

    public WeightedQuickUnionWithPathCompression(T[] components) {
        for (T component : components) {
            this.components.put(component, component);
            this.treeSizes.put(component, 1);
        }
    }

    public void connect(T leftComponent, T rightComponent) {
        Objects.requireNonNull(leftComponent);
        Objects.requireNonNull(rightComponent);

        if (areConnected(leftComponent, rightComponent)) {
            return;
        }

        T leftComponentTree = find(leftComponent);
        T rightComponentTree = find(rightComponent);

        int leftTreeSize = getTreeSize(leftComponentTree);
        int rightTreeSize = getTreeSize(rightComponentTree);
        if (leftTreeSize < rightTreeSize) {
            components.put(leftComponentTree, rightComponentTree);
            treeSizes.put(rightComponentTree, leftTreeSize + rightTreeSize);
        } else {
            components.put(rightComponentTree, leftComponentTree);
            treeSizes.put(leftComponentTree, leftTreeSize + rightTreeSize);
        }
    }

    private T find(T component) {
        while (!component.equals(components.get(component))) {
            components.put(component, components.get(components.get(component))); // Path compression
            component = components.get(component);
        }
        return component;
    }

    private int getTreeSize(T component) {
        return treeSizes.get(component);
    }

    public boolean areConnected(T leftComponent, T rightComponent) {
        Objects.requireNonNull(leftComponent);
        Objects.requireNonNull(rightComponent);
        return find(leftComponent).equals(find(rightComponent));
    }
}


texts:
I have two arrays that I need to compare if their IDs are equal. This is how I am currently doing it:

PFQuery *earnedQuery = [PFQuery queryWithClassName:@"EarnedAchievement"];
[earnedQuery whereKey:@"user" equalTo:[PFUser currentUser]];
[earnedQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

    for (Achievement *achievement in allAchievements) {

        for (PFObject *earnedAchievement in objects) {

            if ([achievement.id isEqualToString:earnedAchievement[@"achievmentId"]]) {

                //user has earned this achievement
                achievement.earned = [NSNumber numberWithBool:YES];
                achievement.earnedDate = earnedAchievement[@"earnedOn"];

            }

        }

    }

    [context save:&error];

}];

Is there a better or more efficient way to do this outside of the two for in loops?


texts: Generate HTML file from Handlebars template and data object

texts:
I have a class called HtmlFile which has a method called generate. This method is responsible for generating an html file from handlebars template and data object provided in the HtmlFile class constructor.

I am confused on what code design should I use for this use case and what variable names to choose.

class HtmlFile {
    public file: any = null;
    private template: any = null;
    private data: any = null;
    constructor(templatePath: string, params: any) {
        this.template = path.resolve(templatePath);
        this.data = params;
    }

    public async generate() {
        try {
            const error = this._validate();
            if (error) {
                throw error;
            }
            const fileContent = fs.readFileSync(this.template, "utf8");
            const html = handlebars.compile(fileContent)(this.data);
            return html;
        } catch (e) {
            throw e;
        }
    }

    private _validate() {
        let errStr: any = null;
        if (typeof this.template !== "string") {
            errStr = `expected template path to be a string, instead got
            ${typeof this.template}`;
        }
        if (typeof this.data !== "object") {
            errStr = `expected data to be an object, instead got ${typeof
            this.data}`;
        }
        return errStr;
    }
}

And I am using this class in the following manner:

let htmlFile = new HtmlFile("./src/templates/sample.hbs", invoiceOptions);
const html: any = await htmlFile.generate();
return html;

I also want suggestions on what variable names I should use in place of htmlFile and html.


texts:
My code seems to work fine. However, I feel like it is a bit too long (fraction.cpp). I really want to create simple, readable, and efficient code.

Sample Run:

Here is the fraction.h file:

#ifndef FRACTION_H
#define FRACTION_H
#include <QString>

class Fraction {

public:
     Fraction();
     Fraction(int numberator, int denominator);
     void set(int numberator, int denominator);
     QString toString() const;
     double toDouble() const;
     int findGCD(int a, int b);
     Fraction simplify();
     Fraction add(const Fraction& other);
     Fraction substract(const Fraction& other);
     Fraction multiphy(const Fraction& other);
     Fraction divide(const Fraction& other);

private:
     int m_Numerator;
     int m_Denominator;
};

#endif // FRACTION_H

Here is the fraction.cpp file:

#include "fraction.h"

// Constructors:
Fraction::Fraction()
    :m_Numerator(0), m_Denominator(0) {}

Fraction::Fraction(int numerator, int denominator)
    :m_Numerator(numerator), m_Denominator(denominator) {
}

// Setter method
void Fraction::set(int numberator, int denominator) {
    m_Numerator = numberator;
    m_Denominator = denominator;
}

// GCD
int Fraction::findGCD(int a, int b) {
    if (a == 0)
        return b;
    return findGCD(b%a, a);
}

// Simplify
Fraction Fraction::simplify() {
    int gcd = findGCD(m_Numerator, m_Denominator);
    return Fraction::Fraction(m_Numerator / gcd, m_Denominator / gcd);
}

double Fraction::toDouble() const {
    return ((double) m_Numerator/m_Denominator);
}

QString Fraction::toString()const {
    return QString("%1 / %2 = %3")
        .arg(m_Numerator)
        .arg(m_Denominator)
        .arg(toDouble());
}

Fraction Fraction::add(const Fraction &other) {
    int numeratorTemp(m_Numerator);
    int denominatorTemp(m_Denominator);

    if (m_Denominator == other.m_Denominator) {
        numeratorTemp = m_Numerator + other.m_Numerator;
    } else {
        numeratorTemp = m_Numerator * other.m_Denominator + other.m_Numerator * m_Denominator;
        denominatorTemp = m_Denominator * other.m_Denominator;
    }
    return Fraction::Fraction(numeratorTemp, denominatorTemp);
}

Fraction Fraction::substract(const Fraction &other) {
    int numeratorTemp(m_Numerator);
    int denominatorTemp(m_Denominator);

    if (m_Denominator == other.m_Denominator) {
        numeratorTemp = m_Numerator - other.m_Numerator;
    } else {
        numeratorTemp = m_Numerator * other.m_Denominator - other.m_Numerator * m_Denominator;
        denominatorTemp = m_Denominator * other.m_Denominator;
    }
    return Fraction::Fraction(numeratorTemp, denominatorTemp);
}

Fraction Fraction::divide(const Fraction &other) {
    int numeratorTemp(m_Numerator);
    int denominatorTemp(m_Denominator);

    numeratorTemp = m_Numerator * other.m_Denominator;
    denominatorTemp = m_Denominator * other.m_Numerator;
    return Fraction::Fraction(numeratorTemp, denominatorTemp);
}

Fraction Fraction::multiphy(const Fraction &other) {
    int numeratorTemp(m_Numerator);
    int denominatorTemp(m_Denominator);

    numeratorTemp  = m_Numerator * other.m_Numerator;
    denominatorTemp = m_Denominator * other.m_Denominator;
    return Fraction::Fraction(numeratorTemp, denominatorTemp);
}

Main.cpp:

#include <QCoreApplication>
#include <iostream>
#include "fraction.h"

int main() {
    using namespace std;

    Fraction frac1(1, 2);
    Fraction frac2(5, 2);

    cout << "Addition: 1/2 + 5/2 = " << frac1.add(frac2).simplify().toString().toUtf8().constData() << "\n";
    cout << "Substraction: 1/2 - 5/2 = " << frac1.substract(frac2).simplify().toString().toUtf8().constData() << "\n";
    cout << "Divide: 1/2 : 5/2 = " << frac1.divide(frac2).simplify().toString().toUtf8().constData() << "\n";
    cout << "Multiplication: 1/2 * 5/2 = " << frac1.multiphy(frac2).simplify().toString().toUtf8().constData() << "\n";
}

Output: https://i.stack.imgur.com/cnT9A.png


texts: Better Way to Show and Hide Items in Project

texts:
I have this code snippet below that I am looking for a way to make smaller if possible.  Any help or suggestions would be appreciated, thanks!

Private Sub ShowAlternateRows(Show As Boolean)
    If Show = True Then
        splitter.Visible = True
        lblAlternateActualPercent.Visible = True
        lblAltEstimated.Visible = True
        lblStaticAltEstimated.Visible = True

        Grid.Cols.Item("Alternate Type").Visible = True
        Grid.Cols.Item("Alternate Start").Visible = True
        Grid.Cols.Item("Alternate End").Visible = True
        Grid.Cols.Item("Alternate Hours").Visible = True
        Grid.Cols.Item("Alternate Burn").Visible = True

        Grid.Cols.Item("Start Estimated").Visible = False
        Grid.Cols.Item("End Estimated").Visible = False
        Grid.Cols.Item("Start Actual").Visible = False
        Grid.Cols.Item("End Actual").Visible = False
        Grid.Cols.Item("Estimated Hours").Visible = False
        Grid.Cols.Item("Actual Hours").Visible = False
        Grid.Cols.Item("Burn Estimated").Visible = False
        Grid.Cols.Item("Object Count").Visible = False
        Grid.Cols.Item("Request Count").Visible = False
        Grid.Cols.Item("Resource Count").Visible = False

        lblStaticActual.Visible = False
        lblActual.Visible = False
        lblActualPercent.Visible = False
        lblStaticEstimated.Visible = False
        lblEstimated.Visible = False
        lblStaticFiltered.Visible = False
        lblFiltered.Visible = False
        lblFilteredPercent.Visible = False

    Else
        splitter.Visible = False
        lblAlternateActualPercent.Visible = False
        lblAltEstimated.Visible = False
        lblStaticAltEstimated.Visible = False

        lblStaticActual.Visible = True
        lblActual.Visible = True
        lblActualPercent.Visible = True
        lblStaticEstimated.Visible = True
        lblEstimated.Visible = True
        lblStaticFiltered.Visible = True
        lblFiltered.Visible = True
        lblFilteredPercent.Visible = True

        Grid.Cols.Item("Start Estimated").Visible = True
        Grid.Cols.Item("End Estimated").Visible = True
        Grid.Cols.Item("Start Actual").Visible = True
        Grid.Cols.Item("End Actual").Visible = True
        Grid.Cols.Item("Estimated Hours").Visible = True
        Grid.Cols.Item("Actual Hours").Visible = True
        Grid.Cols.Item("Burn Estimated").Visible = True
        Grid.Cols.Item("Object Count").Visible = True
        Grid.Cols.Item("Request Count").Visible = True
        Grid.Cols.Item("Resource Count").Visible = True

        Grid.Cols.Item("Alternate Type").Visible = False
        Grid.Cols.Item("Alternate Start").Visible = False
        Grid.Cols.Item("Alternate End").Visible = False
        Grid.Cols.Item("Alternate Hours").Visible = False
        Grid.Cols.Item("Alternate Burn").Visible = False
    End If
End Sub


texts:
This draws scanline of the image to System.Drawing.Graphics. It's quite simple and it's optimized in order to merge neigbour samples with the same color into single rectangle (instead of drawing sample-by-sample in 1x1 rectangles).

I don't like the duplication of this code inside and outside the loop:

updateAlpha(brush, previousColor);
graphics.FillRectangle(brush, previousIndex + positionX, y, i - previousIndex, 1);

Do you know the good way how to follow DRY principle here and to keep code easy to understand? Or this is a kind of perfectionism and all is already fine?

private static void drawGlyphRowToGraphics(int rowIndex, FT_Bitmap glyphBitmap,
    Graphics graphics, float positionX, float positionY, SolidBrush brush)
{
    float y = rowIndex + positionY;

    byte previousColor = 0;
    int previousIndex = 0;
    for (int i = 0; i < glyphBitmap.Width; ++i)
    {
        byte color = (byte)(255 - glyphBitmap.Buffer[i + rowIndex * glyphBitmap.Width]);
        if (i == 0)
            previousColor = color;

        if (color != previousColor)
        {
            updateAlpha(brush, previousColor);
            graphics.FillRectangle(brush, previousIndex + positionX, y, i - previousIndex, 1);

            previousColor = color;
            previousIndex = i;
        }
    }

    if (glyphBitmap.Width > 0)
    {
        updateAlpha(brush, previousColor);
        graphics.FillRectangle(brush, previousIndex + positionX, y, glyphBitmap.Width - previousIndex, 1);
    }
}

private static void updateAlpha(SolidBrush brush, byte gray)
{
    brush.Color = Color.FromArgb(255 - gray, brush.Color.R, brush.Color.G, brush.Color.B);
}


texts: Implementation of Sieve of Eratosthenes algorithm

texts:
I have made an implementation of Sieve of Eratosthenes algorithm in Java, and am not certain that it is as efficient as possible.

I have looked at other peoples implementations on Google, and on this site, which raised concerns for me, as no one has taken a similar approach to me.

public class sieveOfEratosthenes {
    public static void main (String [] args) {
        int maxPrime;
        try (java.util.Scanner tempInput = new java.util.Scanner(System.in)) {
            System.out.println("What number would you like the prime numbers to be generated to?");
            maxPrime = tempInput.nextInt();
            tempInput.close();
        }
        System.out.println("Computing list...");
        long start = System.nanoTime();
        int [] numberList = new int [(maxPrime - 1)];
        boolean [] isPrime = new boolean [(maxPrime - 1)];
        for(int i = 0; i < (maxPrime - 1); i++) {
            numberList[i] = (i + 2);
            isPrime[i] = true;
        }
        int maxTestNum = (int) Math.sqrt(maxPrime);
        int tempAns;
        for(int j = 0; j < maxTestNum; j++) {
            int temp = numberList[j];
            if(isPrime[j] == true) {
                temp = numberList[j];
            }
            for(int k = j; k < (numberList.length - 1); k++) {
                for(int p = 2; p <= numberList.length; p++) {
                    tempAns = temp * p;
                    if(tempAns > maxPrime) {
                        break;
                    }
                    for(int z = 0; z < numberList.length; z++) {
                        if(numberList[z] == tempAns) {
                            isPrime[z] = false;
                        }
                    }
                }
            }
        }
        long stop = System.nanoTime();
        System.out.print("Prime numbers than are <= " + maxPrime + ": ");
        for(int n = 0; n < numberList.length; n++) {
            if (isPrime[n] == true) {
                System.out.print(numberList[n] + " ");
            }
        }
        System.out.println();
        System.out.println("Execution time: " + ((stop - start) / 1e+6) + "ms");
    }
}

The issues I came across whilst creating it were:

What is the best way of storing a list of numbers?
Is there a more efficient way of generating a list of numbers, rather than just using a for loop?
How efficient are arrays? Is there a more efficent 'version' of an array that could have been used to store/access data?


texts: Efficiently finding approximate fraction, with tolerance for fp rounding

texts:
I needed to convert floating point numbers to int/int fractions. Python technically has this functionality, but has issues with rounding errors:

>>> (0.1+0.2).as_integer_ratio()
(1351079888211149, 4503599627370496)

This is what I wrote and I was wondering whether it could be further improved for performance?

def as_fraction(number: float, accuracy: float) -> (int, int):
    whole, x = divmod(number, 1)
    if not x:
        return int(whole), 1
    n = 1
    while True:
        d = int(n/x)
        if n/d-x < accuracy:
            return int(whole)*d+n, d
        d += 1
        if x-n/d < accuracy:
            return int(whole)*d+n, d
        n += 1


texts: Bash function to generate colored output

texts:
I like to user colored output in my interactive shell scripts.

I've been using Ubuntu and bash for a long time, but haven't done much bash scripting.

I'd appreciate a review of this function for generating colored output.

#!/usr/bin/env bash
#
# Function to generate colored output.
#
# The output is specified using a format string and arguments, similar to printf.
#
# All special format specifiers are enclosed in parenthesis.
# Colors start with either "f" for foreground or "b" for background with the
# remainder of the specifier being the color name, starting with a capital
# letter (e.g., fRed or bCyan).
#
# There are a few other specifiers in addition to the colors:
# - %s%         Placeholder; consumes the next argument from the command line
# - %u%         Underline
# - %r$         Reverse video
# - %default%   Default foreground and background color
# - %reset%     Reset all attributes
#
# Example:
#   echoc '%fRed%The value "%r%%s%%fRed%" is not valid for the --trace option' extra
# Result:
#   The value "extra" is not valid for the --trace option
#   with everything except the word extra being red on the default background
#   color and the word extra being reverse-video.
#
unset -f echoc
function echoc()
{
  local       char
  local       code
  local       fmt="${1}"
  local       fmtLen=${#fmt}
  local       i=0
  local       output=''
  local       str=''
  local       tagActive=0

  shift       # Remove the format string.

  #
  # The ANSI color and format codes.
  # Keys that start with "f" are foreground colors.
  # Keys that start with "b" are background colors.
  # Other keys are eight resets or other formatting codes.
  # The "r" and "u" are reverse and underscore, respectively.
  #
  declare -A colors
  colors=(['fBlack']='30' ['fBlue']='34' ['fBrown']='33' ['fCyan']='36')
  colors+=(['fDarkgray']='1;30' ['fDefault']='39' ['fGreen']='32' ['fLavender']='1;34')
  colors+=(['fLightblue']='1;36' ['fLightgray']='37' ['fLightgreen']='1;32')
  colors+=(['fLightpurple']='1;35' ['fMagenta']='35' ['fPink']='1;31' ['fPurple']='35')
  colors+=(['fRed']='31' ['fWhite']='1;37' ['fYellow']='1;33')
  colors+=(['bBlack']='40' ['bBlue']='44' ['bBrown']='43' ['bCyan']='46' ['bDefault']='49')
  colors+=(['bGreen']='42' ['bMagenta']='45' ['bPurple']='45' ['bRed']='41')
  colors+=(['default']='39;49' ['reset']='0')
  colors+=(['r']='7' ['u']='4')

  #
  # Parse the format string, building the output string as we go.
  #
  while [ $i -lt $fmtLen ]
  do
    char="${fmt:i:1}"
    case $char in
      %)
        if [ 0 -eq $tagActive ]
        then
          if [ -n "${str}" ]
          then
            output="${output}${str}"
            str=''
          fi
          tagActive=1
        else # tagActive is true.
          if [ -z "${str}" ]
          then
            output="${output}%" # %% inserts a percent sign.
          else
            if [ 's' == "${str}" ]
            then
              output="${output}${1}\033[0m"
              shift
            else
              code="${colors[$str]}"
              if [ -z "${code}" ]
              then
                echo -e "\033[31mInvalid color name \"${str}\"\033[0m"
              else
                output="${output}\033[${code}m"
              fi
            fi
            str=''
          fi
          tagActive=0
        fi
        ;;

      *)
        str="${str}${char}"
        ;;
    esac
    ((i++))
  done
  if [ -n "${str}" ]
  then
    output="${output}${str}"
  fi
  output="${output}\033[0m"
  echo -e "${output}"

}
export -f echoc


texts: Converting from decimals to roman numerals

texts:
I've submitted the following code for a job interview, and I wanna know if there is anything I can improve on it, or better ways to do the same thing.

const algarismsMap = {
    1 : {
        1 : 'I',
        4 : 'IV',
        5 : 'V',
        9 : 'IX'
    },
    1e1 : {
        1 : 'X',
        4 : 'XL',
        5 : 'L',
        9 : 'XC'
    },
    1e2 : {
        1 : 'C',
        4 : 'CD',
        5 : 'D',
        9 : 'CM'
    },
    1e3: {
        1 : "I\u0305",
        4 : 'I\u0305V\u0305',
        5 : 'V\u0305',
        9 : 'I\u0305X\u0305'
    },
    1e4: {
        1 : "X\u0305",
        4 : 'X\u0305L\u0305',
        5 : 'L\u0305',
        9 : 'X\u0305C\u0305'
    },
    1e5 : {
        1 : "C\u0305",
        4 : 'C\u0305D\u0305',
        5 : 'D\u0305',
        9 : 'C\u0305M\u0305'
    }
}

const divisors = Object.keys( algarismsMap ).reverse()

const romanizeNumber = module.exports = function( n ) {

    // not throwing an error because this can happen while recursing
    if ( n <= 0 ) {
        return ''
    }

    // welp, for numbers greater than 3999999 we break roman rules of not repeating the same algarism more than 3 times,
    //   or we need to add more dashes, which is not really documented, at least I could not find some reliable source about it.
    if ( n >= 4e6 ) {
        throw new Error( 'The max supported number to be converted is 3999999' )
    }

    let romanizedNumber = ''

    // Some special cases for the M algarism.
    if ( n >= 1e3 && n <= 3999 ||  n >= 1e6 && n <= 3999999 ) {

        romanizedNumber += ( n >= 1e6 ? 'M\u0305' : 'M' ).repeat( n / (n >= 1e6 ? 1e6 : 1e3 ) )
        romanizedNumber += romanizeNumber( n % (n >= 1e6 ? 1e6 : 1e3 ) )

    } else {

        for ( let i = 0; i < divisors.length; i++ ) {

            const currDivisor = divisors[i]|0
            const currDivisorInfo = algarismsMap[currDivisor]

            const internalDivisors = Object.keys( currDivisorInfo ).reverse()

            // The number is not divisible by this one, keep going (we could just check if n < currDivisor duh)
            if ( n % currDivisor === n ) {
                continue
            }

            for ( let k = 0; k < internalDivisors.length; k++ ) {

                const currInternalDivisor = internalDivisors[k]|0
                const currInternalDivisorAlgarism = currDivisorInfo[currInternalDivisor]

                if ( n >= currInternalDivisor * currDivisor ) {

                    // the 1 check here is basically for the same motive than the 'M' check above.
                    romanizedNumber += currInternalDivisor === 1 ? currInternalDivisorAlgarism.repeat( n / currDivisor ) : currInternalDivisorAlgarism

                    romanizedNumber += romanizeNumber( n % (currInternalDivisor * currDivisor) )

                    return romanizedNumber
                }
            }
        }

    }

    return romanizedNumber
}

The \u0305 is the unicode for the combining overline character: https://en.wikipedia.org/wiki/Overline


texts:
Solved the classic Tower of Hanoi problem in Ruby, using recursion. Would love your feedback on this.

# Excellent explanation of the solution at
# http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/13/hanoi.html

Move =
  Struct.new :disk, :from, :to do
    def to_s
      "Disk #{disk}: #{from} -> #{to}"
    end
  end

def spare_peg(from, to)
  # returns the peg that is not 'from' nor 'to'
  # e.g. if from="A", to="C" ... then spare="B"
  [*"A".."C"].each {|e| return e unless [from, to].include? e}
end

def hanoi(num, from, to)
  if num == 1 # base case
    return [Move.new(num, from, to)]
  end

  spare = spare_peg(from, to)
  moves = hanoi(num - 1, from, spare) # move everything to the spare peg
  moves << Move.new(num, from, to) # move the sole remaining disk to the 'to' peg
  moves += hanoi(num - 1, spare, to) # move all the disks on top of the 'to' peg
end

Sample output:

  puts hanoi(3, "A", "B").each {|move| move.to_s}

Disk 1: A -> B
Disk 2: A -> C
Disk 1: B -> C
Disk 3: A -> B
Disk 1: C -> A
Disk 2: C -> B
Disk 1: A -> B


texts:
I am making countdown app with multiple records, so I am using UITableView to show that records and countdown dates. What I do is just take one timer and reload cells on every second. Is this a best approach to reload visible cells on every second or is there another better approach there?

updateCellContentsTimer = Timer.scheduledTimer(timeInterval: 1,
            target: self,
          selector: #selector(ViewController.updateCells),
          userInfo: nil, repeats: true)

// MARK: Custom Functions

func updateCells() {
    let indexPathsArray = tableView.indexPathsForVisibleRows
    for indexPath in indexPathsArray! {
        let cell = tableView.cellForRow(at: indexPath) as! CountdownTableViewCell

        cell.timeLeftLabel.text = progress + "hours:minutes:seconds"
    }
}


texts: Calculate the average score of groups and each student, C

texts:
I have a file containing information about the session of students. The structure of this file is: group number, student name, exams, and tests.

debt() function find and print the names of underachieving students.
student_score() calculate the average score of groups
group_score() calculate the average score of each student.

So, this is my program and maybe I can make something better?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#include <locale.h>

#define N 50

void debt();
void student_score();
void group_score();

struct STUDENTS {
  int group;
  char name[100];
  char test[15];
  int exam;
};

struct STUDENTS student_list[N];

int main() {
  FILE *file;
  int choice;
  char buffer[200];
  int i = 0;

  file = fopen("students.txt", "r");

  if (file == NULL) {
    puts("students.txt не найден");
    return 1;
  }

  while (fgets(buffer, sizeof buffer, file) != NULL) {
    sscanf(strdup(buffer), "%d %[^0-9] %d %s", &student_list[i].group, student_list[i].name, &student_list[i].exam, student_list[i].test);
    i++;
  }
  fclose(file);
  int student_list_size = i;

  do {
    puts("\nВыберите номер пункта меню:");
    puts("1 - Cтуденты, имеющие задолженности");
    puts("2 – Средний балл каждого студента");
    puts("3 – Средний балл всей группы");
    puts("4 - Выход\n");

    scanf("%d", &choice);

    switch (choice) {
      case 1:
        debt(student_list_size);
        break;
      case 2:
        student_score(student_list_size);
        break;
      case 3:
        group_score(student_list_size);
        break;
      case 4:
        break;
      default:
        puts("\nНужно вводить номер пункта от 1 до 4");
        break;
    }
  } while (choice != 4);

  return 0;
}

void debt(int student_list_size) {
  int counter_debt;
  wchar_t test_wchar[15];
  wchar_t * pch;

  setlocale(LC_ALL, "");

  for (int i = 0; i < student_list_size; i++) {
    counter_debt = 0;
    mbstowcs(test_wchar, student_list[i].test, 15);

    pch = wcschr(test_wchar, L'н');
    while (pch != NULL) {
      counter_debt++;
      pch = wcschr(pch + 1, L'н');
    }

    if (counter_debt > 0) {
      printf("%d %s: %d\n", student_list[i].group, student_list[i].name, counter_debt);
    }
  }
}

void student_score(int student_list_size) {
  int exam;
  int average;
  int digit;
  int counter_digits;

  for (int i = 0; i < student_list_size; i++) {
    average = 0;
    digit = 0;
    counter_digits = 0;
    exam = student_list[i].exam;

    while (exam) {
      digit = exam % 10;
      average += digit;
      counter_digits++;
      exam = exam / 10;
    }

    printf("%d %s: %.1f\n", student_list[i].group, student_list[i].name, (double)average / counter_digits);
  }
}

void group_score(int student_list_size) {
  int exam;

  struct GROUP_SCORE {
    int group_score;
    int students_counter;
  };
  struct GROUP_SCORE group_list[5000] = {0};

  for (int i = 0; i < student_list_size; i++) {
    group_list[ student_list[i].group ].students_counter += 1;
    exam = student_list[i].exam;
    while (exam) {
      group_list[ student_list[i].group ].group_score += exam % 10;
      exam = exam / 10;
    }
  }

  for (int j = 0; j < 5000; j++) {
    if (group_list[j].group_score > 0) {
      printf("%i: %.1f\n", j, (double)group_list[j].group_score / group_list[j].students_counter);
    }
  }
}

students.txt:

4272 Галкин Г. А. 5445 ззззз
4273 Константинопольский А. А. 4333 знзнз
4273 Курочкин А. А. 3433 знзнн
4272 Козлов И. И. 4443 ззззн


texts:
I have a website that offers to search documents from local hearings conducted, stored on a network file server.  I need to take in the search term and search a bunch of .docx (roughly 4500) files.  They are not large,  < 150 kb mostly, but it runs very slow downloading the files into the stream. I'm sure there's a better way to write the search, (perhaps multi processing) but I don't know how to tune it up and speed the search up.  The search itself is taking over 3 minutes.

bool found = false;
Hearing h = new Hearing();
Stream str = null;
MemoryStream str2 = new MemoryStream();
HttpWebRequest fileRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse fileResponse = (HttpWebResponse)fileRequest.GetResponse();
str = fileResponse.GetResponseStream();
str.CopyTo(str2);
str2.Position = 0;
using (WordprocessingDocument wpd = WordprocessingDocument.Open(str2, true))
{
    string docText = null;
    using (StreamReader sr = new StreamReader(wpd.MainDocumentPart.GetStream()))
    {
        docText = sr.ReadToEnd();
        found = docText.ToUpper().Contains(txtBasicSearch.Text.ToUpper());
        if (found)
        {
            hearingArrayList.Add(h);
            foundCount++;
        }
    }
}


texts: Refactoring String manipulating method with TDD

texts:
I'd like to refactor my extractSimplePromptName test so it does the same but it's "prettier", hence less code. As far as looking at it, it seems like it could be refactored so it does the same thing, but it's just less code. I'm just fairly new to programming so having a hard time seeing where I should make the changes.

Guessing it has something to do with putting some stuff out of the first if sentence or perhaps just removing something that doesn't do anything.

I just ain't that certain, and I'd really like some help so I can get better at doing decent code.

@Test
public void makeSimpleName1() {
    String promptNameOrg = "20129142\\1234";

    String simplePromptName = extractSimplePromptName(promptNameOrg);
    Assert.assertEquals("1234", simplePromptName);
}

@Test
public void makeSimpleName2() {
    String promptNameOrg = "80808080\\159;20129142\\1234";

    String simplePromptName = extractSimplePromptName(promptNameOrg);
    Assert.assertEquals("1234", simplePromptName);
}

@Test
public void makeSimpleName3() {
    String promptNameOrg = "159;1234";

    String simplePromptName = extractSimplePromptName(promptNameOrg);
    Assert.assertEquals("1234", simplePromptName);
}

private String extractSimplePromptName(String promptNameOrg) {
    String simplePromptName = "";
    if (promptNameOrg != null) {
        if (promptNameOrg.contains(";") || promptNameOrg.contains("\\")) {
            List<String> splitPrompts = Arrays.asList(promptNameOrg.split(";"));

            String promptName = splitPrompts.get(splitPrompts.size() - 1);
            if (promptName.contains("\\")) {
                String[] split = promptName.split("\\\\");
                List<String> splitPromptName = Arrays.asList(split);
                simplePromptName = splitPromptName.get(splitPromptName.size() - 1);
            } else {
                simplePromptName = promptName;
            }

        } else {
            simplePromptName = promptNameOrg;
        }

    }
    return simplePromptName;
}


texts:
I have the following mockup that I need some feedback on how I might improve the url_decode function to make it faster and use less memory. There are a couple of requirements.  I have to use the StringArg and StringReturn structs. I also need to completely decode the string.  I am aware of double encoded attacks, but this is for data mining and I need to get the string fully decoded, hence the while loop.

Please have a look at function StringReturn* url_decode(char* line) and suggest anything that I can do to improve the speed or reduce the memory used.

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <ctype.h>

struct StringArg
{
    int length;
    char* data;
    StringArg(const char* inData)
    {
        length = strlen(inData);
        data = new char[length+1];
        strcpy(data, inData);
    }
};

struct StringReturn
{
    int size;
    char* data;
    StringReturn(int inSize)
    {
        size = inSize;
        data = new char[size+1];
    }
};

StringArg* stringArg(char* line)
{
    return new StringArg(line);
}

StringReturn* stringReturnInfo(int size)
{
    return new StringReturn(size);
}

StringReturn* url_decode(char* line)
{
        StringArg *str;
        str = stringArg(line);

        int lengths = str->length;
        char* urlData = new char[lengths+1];
        char* fmt = new char[4];
        memcpy(urlData, str->data, str->length);
        urlData[lengths] = 0;
        bool bFoundChar = false;

        int j = 0;

        do
        {
                j = 0;
                bFoundChar = false;
                for (int i = 0; i < lengths; i++)
                {
                        char ch = urlData[i];
                        if (ch == '+')
                        {
                                urlData[j++] = ' ';
                        }
                        else if (ch == '%' && i+2 < lengths &&  isxdigit(urlData[i+1]) &&  isxdigit(urlData[i+2]))
                        {
                                bFoundChar = true;
                                fmt = new char[4];

                                fmt[0] = urlData[++i];
                                fmt[1] = urlData[++i];
                                fmt[2] = 0;

                                urlData[j++] = (char)strtol(fmt, NULL, 16);

                        }
                        else {
                                urlData[j++] = ch;
                        }
                }
                lengths = j;
        }while (bFoundChar);

        StringReturn *ret = stringReturnInfo(j);
        ret->size = j;

        memcpy(ret->data, urlData, j);
        delete urlData;
        delete fmt;

        return ret;

}

void test_decode(char* line)
{
    StringReturn *str = url_decode(line);
    printf(str->data);
}

int main(int argc, const char * argv[])
{

    test_decode("bob.com?url=http%3A%2F%2Fsteve.com%3Furl%3Dhttp%253A%252F%252Fjohn.com");

    return 0;
}


texts: SPOJ problem - The last digit of a number to a power (follow up)

texts:
As a follow up to my post here. Please refer to the problem statement in that post.

I have edited this code to make it time efficient, but doing so the size of the source file has crossed the limit of 700 bytes. How do I reduce the file size?

#include <stdio.h>

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        long long int base,exponent;
        scanf("%lld%lld",&base,&exponent);
        if(exponent==0)
        {
            printf("1\n");
        }
        else
        {
            int i;
            int dig[5];
            dig[0]=1;
            for(i=1;i<=4;i++)
            {
                dig[i]=(base*dig[i-1])%10;
            }
            if(exponent%4==0)
                printf("%d\n",dig[4]);
            else if(exponent%4==1)
                printf("%d\n",dig[1]);
            else if(exponent%4==2)
                printf("%d\n",dig[2]);
            else if(exponent%4==3)
                printf("%d\n",dig[3]);
        }
    }
    return 0;
}


texts:
I've got an app that's got an activity/timeline like view. Since I don't want to retrieve the entire timeline every time, I'm caching all the events.

Currently, this is how I go about it:

- (void)saveEventArray:(NSMutableArray *)eventArray {
    // save hier in bg
    dispatch_async(kAsyncQueue, ^{
        __block int loopCount = 0;
        NSArray *copyEventArray = [eventArray copy];
        NSMutableArray *archiveArray = [NSMutableArray arrayWithCapacity:copyEventArray.count];

        if([copyEventArray count] == 0){ // If it's an empty array to save, it won't loop
            NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
            [userData setObject:[[NSMutableArray alloc]init] forKey:@"events"];
            NSLog(@"save is done, no events left in eventarray");
        }

        for (NSMutableDictionary *event in copyEventArray) {
            // PFFile isn't easy to encode, but UIImage is, so whenever we encounter a PFFile, we convert it to UIImage
            id imageFile = [event objectForKey:@"img"];
            if([imageFile isKindOfClass:[PFFile class]]){
                [imageFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
                    if (!error) {
                        UIImage *image = [UIImage imageWithData:imageData];
                        [event setObject:image forKey:@"img"]; // the PFFile is now replaced for an UIImage
                        NSData *eventEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:event];
                        [archiveArray addObject:eventEncodedObject];
                        loopCount++;

                        if(loopCount == [copyEventArray count]){ // when done looping, save it all
                            NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
                            [userData setObject:archiveArray forKey:@"events"];
                            NSLog(@"save is done");

                        }
                    }
                }];
            } else {
                loopCount++;
                NSData *eventEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:event];
                [archiveArray addObject:eventEncodedObject];

                if(loopCount == [copyEventArray count]){ // when done looping
                    NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
                    [userData setObject:archiveArray forKey:@"events"];
                    NSLog(@"save is done");
                }
            }

        }
    });

}

However, I noticed that this takes insane amounts of storage and the app grows very quickly in size when doing this. Is there a better/more efficient way for this?


texts: Exponentiation using while loop in Python

texts:
I could not think of any better way to raise to power, except this, but how do I refactor it? I should only use while loop, not for loop, not x**y.

I shall not use pow(x,y)

result = 1
base = 3
counter = 1
degree = 4
while counter <= degree:
        result = base * result
        counter += 1
        print("counter %d and the result %d" %(counter, result))
print("result is ", result)


texts:
I want you to give me some feedback on how I could make it better or simpler.

public class NonRecursiveTraversal {

    private TreeNode root;

    private static class TreeNode {
        TreeNode left;
        TreeNode right;
        int item;

        TreeNode (TreeNode left, TreeNode right, int item) {
            this.left = left;
            this.right = right;
            this.item = item;
        }
    }

    public void createBinaryTree (Integer[] arr) {
        if (arr == null)  {
            throw new NullPointerException("The input array is null.");
        }

        root = new TreeNode(null, null, arr[0]);

        final Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);

        final int half = arr.length / 2;

        for (int i = 0; i < half; i++) {
            if (arr[i] != null) {
                final TreeNode current = queue.poll();
                final int left = 2 * i + 1;
                final int right = 2 * i + 2;

                if (arr[left] != null) {
                    current.left = new TreeNode(null, null, arr[left]);
                    queue.add(current.left);
                }
                if (right < arr.length && arr[right] != null) {
                    current.right = new TreeNode(null, null, arr[right]);
                    queue.add(current.right);
                }
            }
        }
    }

    public void preOrder() {
        if (root == null) return;

        final Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.add(root);

        while (!stack.empty()) {
            TreeNode node = stack.pop();
            System.out.print(node.item + " ");
            // LIFO
            if (node.right != null) stack.push(node.right);
            if (node.left != null) stack.push(node.left);
        }
    }

    public void reverseOrder() {
        if (root == null) return;

        final Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.add(root);

        while (!stack.empty()) {
            TreeNode node = stack.pop();
            System.out.print(node.item + " ");
            // LIFO
            if (node.left != null) stack.push(node.left);
            if (node.right != null) stack.push(node.right);
        }
    }

    public void inOrder() {
        if (root == null) return;

        final Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode node = root;

        while (!stack.isEmpty() || node != null) {
            if (node != null) {
                stack.add(node);
                node = node.left;
            } else {
               node = stack.pop();
               System.out.print(node.item + " ");
               node = node.right;
            }
        }
    }

    public void postOrder  () {
        if (root == null) return;

        final Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode node = root;

        while (!stack.isEmpty() || node != null) {
            while (node != null) {
                if (node.right != null) stack.add(node.right);
                stack.add(node);
                node = node.left;
            }

            node = stack.pop();

            // (node.right) != null means this node is parent of that tiny subtree
            // stack.pop != null ensures it was not the root.
            if (node.right != null && !stack.isEmpty() && node.right == stack.peek()) {
                TreeNode nodeRight = stack.pop();
                stack.push(node);
                node = nodeRight;
            } else {
                System.out.print(node.item + " ");
                node = null;
            }
        }
    }
}

Also, please correct my complexities: time and space both being \$O(n)\$.


texts:
If we have a set of classes or structs such as:

struct Point
{
    float x;
    float y;
};

struct Square
{
    Point topLeft;
    float width;
};

struct Circle
{
    float radius;
    Point middle;
};

If we need to add some functionality to to these, does something like below make sense?

inline Point middleOf(const Square &square)
{
    float halfWidth(square.width/2.0f);
    return Point{
        square.topLeft.x + halfWidth,
        square.topLeft.y + halfWidth};
}

inline Point middleOf(const Circle &circle)
{
    return circle.middle;
}

class MoveSquare
{
public:
    MoveSquare(Square &squareToMove)
    :
    squareToMove(squareToMove)
    {}

    void to(const Point &target)
    {
        squareToMove.topLeft = offsetHalfWidth(target);
    }

private:
    Point offsetHalfWidth(Point p)
    {
        const float halfWidth(squareToMove.width / 2.0f);
        return Point{
            p.x - halfWidth,
            p.y - halfWidth};
    }

private:
    Square &squareToMove;
};

class MoveCircle
{
public:
    MoveCircle(Circle &circle)
    :
    circleToMove(circle)
    {}

    void to(Point position)
    {
        circleToMove.middle = position;
    }

private:
    Circle &circleToMove;
};

inline MoveSquare move(Square &square)
{
    return MoveSquare{square};
}

inline MoveCircle move(Circle &circle)
{
    return MoveCircle{circle};
}

The main idea is being able to have code that reads like a sentence. Such as:

int main() {

    Square aSquare;
    aSquare.topLeft = Point{1,1};
    aSquare.width = 3;

    Circle aCircle;
    aCircle.middle = Point{1,1};
    aCircle.radius = 2;

    move(aSquare).to(Point{1,1});
    move(aSquare).to(middleOf(aCircle));

    move(aCircle).to(middleOf(aSquare));

    return 0;
}


texts: Correcting duplicate names in generic array - follow up

texts:
Follow Up question of : Correcting duplicate names in array

I have an array of file names. For example:

FileContent[] files =
{
    new FileContent() {Content = threeItems, Name = "one.zip" },
    new FileContent() {Content = fiveItems, Name = "one.zip" },
    new FileContent() {Content = sevenItems, Name = "one.zip" },
    new FileContent() {Content = threeItems, Name = "two.zip" },
    new FileContent() {Content = fiveItems, Name = "two.zip" },
    new FileContent() {Content = sevenItems, Name = "two.zip" },
};

Model:

public sealed class FileContent
{
    public byte[] Content { get; set; }

    public string Name { get; set; }
}

And I've developed the following method to correct duplicate names. What the method does is just change duplicate names. I am just adding incremented value for the next duplicated value. For example, my developed method ChangingDuplicateNames(string[] files)correct the previous array to:

FileContent[] files =
{
    new FileContent() {Content = threeItems, Name = "one.zip" },
    new FileContent() {Content = fiveItems, Name = "one(1).zip" },
    new FileContent() {Content = sevenItems, Name = "one(2).zip" },
    new FileContent() {Content = threeItems, Name = "two.zip" },
    new FileContent() {Content = fiveItems, Name = "two(1).zip" },
    new FileContent() {Content = sevenItems, Name = "two(2).zip" },
};

And implementation of ChangingDuplicateNames(FileContent[] files) is:

private FileContent[] ChangingDuplicateNames(FileContent[] files)
{
    //Creating a dicitonary to store duplicated values. "Key" of dictionary
    //is duplicated name, "Value" of dictionary is number to add for name
    Dictionary<string, int> duplicateNames = files.GroupBy(x => x.Name)
            .Where(group => group.Count() > 1)
            .ToDictionary(grouped => grouped.Key, grouped => 0);

    if (duplicateNames.Count == 0)
       return files;

    int namesLength = files.Length;
    string actualName = string.Empty;
    for (int indexArray = 0; indexArray < namesLength; indexArray++)
    {
        int value;
        bool isDuplicate = duplicateNames
           .TryGetValue(files[indexArray].Name, out value);
        if (isDuplicate)
        {
           actualName = files[indexArray].Name;
           if (value == 0)
              files[indexArray].Name = files[indexArray].Name;
           else
           {
              //Adding increment to the mext duplicate name
              string fileNameWithoutExtension = Path
                  .GetFileNameWithoutExtension(files[indexArray].Name);
              string fileExtension = Path
                  .GetExtension(files[indexArray].Name);
              files[indexArray].Name = fileNameWithoutExtension + "(" + value + ")"
+ fileExtension;
           }
           duplicateNames[actualName] = ++value;
        }
    }
    return files;
}

And my question is: Is it possible to improve this algorithm? I mean could be this code smaller?

Maybe I should not iterate through the all array of names, but I cannot figure out how I can change names in files without iterating through all array. Thanks in advance.


texts:
I am building a small DSL for iOS' autolayout feature. Obviously I want to have a typesafe way to define autolayouts instead of doing VSL. I came up with the following:

//in reality this will be a Xamarin/iOS View
type View =
     | View

type Constraint =
     | Max of int
     | Min of int
     | Eq of int
     | Both of int * int

type Element =
     | Gap of Constraint
     | Part of View * Constraint

let horizontal superview : Element list = []

let max v = Max v
let min v = Min v
let eq v = Eq v
let minmax min max = Both(min, max)

let gap c es = Gap c :: es
let view v c es = Part (v, c) :: es

//transform needs to implement the real autolayouting.
//not yet done
let transform es = List.rev es

let super_view, left_view, middle_view, right_view = View, View, View, View

horizontal super_view
    |> gap (min 20)
    |> view left_view (min 20)
    |> gap (max 30)
    |> view middle_view (eq 45)
    |> gap (eq 50)
    |> view right_view (minmax 20 100)
    |> gap (max 0)
    |> transform

I am sort of content with the design so far; for example, it has a pretty "fluid" touch to it. However I am asking myself if there are better ways to do it.

One particular issue is the simple fact that every definition is a intersection of "gaps" and "views" starting with a "gap" and ending with a "gap". Is there a possibility to "encode" such a design into types instead of doing it via runtime exceptions (which I would do now).


texts: Calculate the Hamming difference between two DNA strands

texts:
Write a program that can calculate the Hamming difference between two DNA strands.

  GAGCCTACTAACGGGAT
     CATCGTAATGACGGCCT
     ^ ^ ^  ^ ^    ^^

  The Hamming distance between these two DNA strands is 7.

import java.util.Optional;

public class Hamming {
  public static int compute(String s1, String s2) {
    validateInputs(s1, s2);

    int hammingDistance = 0;
    int stringLength = s1.length();

    for (int i = 0; i < stringLength; i++) {
      if (s1.charAt(i) != s2.charAt(i)) {
        hammingDistance++;
      }
    }
    return hammingDistance;
  }

  private static void validateInputs(String s1, String s2) {
    if (s1.length() != s2.length()) {
      throw new IllegalArgumentException();
    }
  }
}

Test suite:

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import org.junit.Test;

public class HammingTest {

    @Test
    public void testNoDifferenceBetweenIdenticalStrands() {
        assertThat(Hamming.compute("A", "A"), is(0));
    }

    @Test
    public void testCompleteHammingDistanceOfForSingleNucleotideStrand() {
        assertThat(Hamming.compute("A", "G"), is(1));
    }

    @Test
    public void testCompleteHammingDistanceForSmallStrand() {
        assertThat(Hamming.compute("AG", "CT"), is(2));
    }

    @Test
    public void testSmallHammingDistance() {
        assertThat(Hamming.compute("AT", "CT"), is(1));
    }

    @Test
    public void testSmallHammingDistanceInLongerStrand() {
        assertThat(Hamming.compute("GGACG", "GGTCG"), is(1));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testValidatesFirstStrandNotLonger() {
        Hamming.compute("AAAG", "AAA");
    }

    @Test(expected = IllegalArgumentException.class)
    public void testValidatesOtherStrandNotLonger() {
        Hamming.compute("AAA", "AAAG");
    }

    @Test
    public void testLargeHammingDistance() {
        assertThat(Hamming.compute("GATACA", "GCATAA"), is(4));
    }

    @Test
    public void testHammingDistanceInVeryLongStrand() {
        assertThat(Hamming.compute("GGACGGATTCTG", "AGGACGGATTCT"), is(9));
    }

}

Questions:

Am I using the correct data structures?
Can I improve performance? Right now it seems to be \$Θ(n)\$ since it has to check all the characters in the string.


texts: Parsing multiple line records using Java 8 Streams

texts:
There was a suggestion in this StackOverflow question to move this question here. I added some more information and restructured the question a bit.

I'm trying to parse the following file which contains information in the following format:

  TABLE_NAME

  VARIABLE_LIST_OF_COLUMNS

  VARIABLE_NUMBER_OF_ROWS (Seperated by a tab seperator)

An example (using ',' as the seperator for the question; actual seperator is a tab):

  STUDENTS

  ID

  NAME

  1,Mike

  2,Kimberly

The idea is to build a list of insert sql statements (context for the code snippet). So the output would be (ignore numeric/null values for now):

  INSERT INTO STUDENTS (ID, NAME) VALUES ('1','Mike');

  INSERT INTO STUDENTS (ID, NAME) VALUES ('2','Kimberly');

What I want to know is whether this kind of multiline parsing is at all possible using java 8 streams API? This is what I have at the moment:

public final class StatementGeneratorMain {

    public static void main(final String[] args) throws Exception{
        List<String> fileNames = Arrays
            .asList("STUDENTS.txt");
        fileNames.stream()
            .forEach(fileName -> {
                String tableName;
                List<String> columnNames;
                List<String[]>  dataRows;
                try (BufferedReader br = getBufferedReader(fileName)) {
                    tableName = br.lines().findFirst().get();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                try (BufferedReader br = getBufferedReader(fileName)) {
                    //skip the first line because its been processed.
                    columnNames = br.lines().skip(1).filter(v -> v.split("\t").length == 1).collect(toList());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                try (BufferedReader br = getBufferedReader(fileName)) {
                    //skip the first line and the columns length to get the data
                    //columns are identified as being splittable on the delimiter
                    dataRows = br.lines().skip(1 + columnNames.size()).map(s -> s.split("\t"))
                        .collect(toList());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                String columns = columnNames.stream().collect(joining(",","(",")"));

                List<String> dataRow = dataRows.stream()
                    .map(arr -> Arrays.stream(arr).map(x -> "'" + x + "'").collect(joining(",", "(", ")")))
                    .map(row -> String.format("INSERT INTO %s %s VALUES %s;", tableName, columns, row))
                    .collect(toList());

                dataRow.forEach(l -> System.out.println(l));
            });
    }

    private static BufferedReader getBufferedReader(String fileName) {
        return new BufferedReader(new InputStreamReader(StatementGeneratorMain.class.getClassLoader().getResourceAsStream(
            fileName)));
    }
}

This piece of code does the job for me, but I don't really like it because I read the same file thrice (once for table name, again to deduce the columns, again to get the rows). I also don't think that it is proper functional style.

What I am looking for is a more elegant way to do this kind of multiline/multirecord parsing using the streams API.

What I thought about:

Using Files.lines() instead of BufferedReader.
Using partitioningBy() instead of filter().collect(toList()) when parsing the columns, then true values goes into the column list and false values goes into the dataRows list.

I'm not too particular about stuff like numeric column and null values at this point.


texts:
I have a task which checks the status of a process running on a Linux server using a shell. The task should report as failed when the status is NOT RUNNING. The following works but is there a better way of checking the status string in the command.

  - name: check status of NC services and processes
    become: yes
    become_method: sudo
    become_user: nc
    environment:
         PATH: "{{ ncpath }}"
    shell: nco_pa_status -server yyyy -password xxxx
    register: command_result
    failed_when: >
      'RUNNING' not in command_result.stdout or
      'PENDING' in command_result.stdout or
      'WAITING' in command_result.stdout or
      'STARTING' in command_result.stdout or
      'DEAD' in command_result.stdout or
      'ERROR' in command_result.stdout

  - debug:
      msg="{{ command_result.stdout }}"
    tags: nervecenter-status

command_result.stdout looks something like the one below. If any process is not running the status will have any of the following: PENDING, WAITING, STARTING, DEAD, ERROR.

 -------------------------------------------------------------------------------
 Service Name         Process Name         Hostname   User      Status      PID
 -------------------------------------------------------------------------------
 Core                 ObjectServer         xxxx      nco       RUNNING    1234
                      Proxy                xxxx      root      RUNNING     256
 -------------------------------------------------------------------------------


texts:
I am writing a java program that will print current market values from a websites api. I used gson to parse the incoming json and Timer to run it every 5 minutes. I was wondering if this was the best approach. I will eventually have it update a server with this information.

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;

public class Main {
public static void main(String[] args) {
    Timer timer = new Timer();

    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            String requestURL = "https://bittrex.com/api/v1.1/public/getmarketsummaries";
            URL request;
            BufferedReader reader = null;
            try {
                request = new URL(requestURL);
                reader = new BufferedReader(new InputStreamReader(request.openStream()));
            } catch (IOException e) {
                e.printStackTrace();
            }

            JsonReader jsonReader = new JsonReader(reader);
            JsonParser jsonParser = new JsonParser();
            JsonObject obj = jsonParser.parse(jsonReader).getAsJsonObject();
            JsonArray array = obj.getAsJsonArray("result");

            for (JsonElement t : array) {
                JsonObject obj2 = t.getAsJsonObject();

                System.out.println("Market Name: " + obj2.get("MarketName").getAsString());
                System.out.println("Last: " + obj2.get("Last").getAsBigDecimal());
                System.out.println("Base Volume: " + obj2.get("BaseVolume").getAsBigDecimal());
                //System.out.println(LocalDateTime.now());
            }

            //write your code here
            System.out.print(new Date() + "\n");
        }
    }, 0, 300000);
}
}


texts: Excel column string to row number and vice versa

texts:
Excel column letters to actual numbers, if you recall, Excel names its columns with letters from A to Z, and then the sequence goes AA, AB, AC... AZ, BA, BB, etc.
  You have to write a function that accepts a string as a parameter (like "AABCCE") and returns the actual column number. And then do the exact reverse, given column number return the column name.

Also verify complexity: \$O(\log n)\$, where \$n\$ is the input number while \$\log\$ is to base the base being considered (hexa, decimal or binary etc.).

public final class Excel {

    private Excel() {}

    public static int getExcelColumnNumber(String column) {
        int result = 0;
        for (int i = 0; i < column.length(); i++) {
            result *= 26;
            result += column.charAt(i) - 'A' + 1;
        }
        return result;
    }

    public static String getExcelColumnName(int number) {
        final StringBuilder sb = new StringBuilder();

        int num = number - 1;
        while (num >=  0) {
            int numChar = (num % 26)  + 65;
            sb.append((char)numChar);
            num = (num  / 26) - 1;
        }
        return sb.reverse().toString();
    }

    public static void main(String[] args) {
         Assert.assertEquals(53, getExcelColumnNumber("BA"));
         Assert.assertEquals("BA", getExcelColumnName(53));

         Assert.assertEquals(703, getExcelColumnNumber("AAA"));
         Assert.assertEquals("AAA", getExcelColumnName(703));

         Assert.assertEquals(26, getExcelColumnNumber("Z"));
         Assert.assertEquals("Z", getExcelColumnName(26));

         Assert.assertEquals(702, getExcelColumnNumber("ZZ"));
         Assert.assertEquals("ZZ", getExcelColumnName(702));

    }
}


texts: Solving first- and second-degree degree polynomials

texts:
I was writing a bit of code and I was just wondering if I was doing it the right way. I know all the syntax is right and It all works perfectly. I was just wondering if I'm doing it the right way. Should I have another infrastructure, am I following the MVC correctly (there is no V yet, it's mostly just a model). Is this program extensible and enhanceable enough?

It's a very simple program that finds the zeroes of either a first degree polynomial

$$ a x + b = 0 $$

or second degree polynomial.

$$ a x^2 + b x + c = 0 $$

First.h:

#import <Foundation/Foundation.h>

@interface First : NSObject
@property double a, b, x;

- (id) initWithAValue: (double) aValue andBValue: (double) bValue;
- (double) calculate;
@end

First.m:

#import "First.h"

@implementation First
-(id)initWithAValue:(double)aValue andBValue:(double)bValue
{
    self = [super init];
    if (self) {
        self.a = aValue;
        self.b = bValue;

    }
    return self;
}
- (double) calculate {
    self.x = (self.b - 2 * self.b)/self.a;
    return self.x;

}
@end

Second.h:

#import <Foundation/Foundation.h>

@interface Second : NSObject
@property double a,b,c,x1,x2,d;
- (id) initWithAValue: (double) aValue andBValue: (double) bValue andCValue: (double) cValue;
- (double) calculateX1;
- (double) calculateX2;
- (double) calculateD;
@end

Second.m:

#import "Second.h"

@implementation Second
- (id)initWithAValue:(double)aValue andBValue:(double)bValue andCValue:(double)cValue
{
    self = [super init];
    if (self){
        //TODO: check if a = 0
        self.a = aValue;
        self.b = bValue;
        self.c = cValue;
    }
    return self;
}
-(double)calculateD
{
    //TODO: Check if d < 0
    self.d = (self.b * self.b)-(4 * self.a * self.c);
    return self.d;
}
-(double)calculateX1
{
    self.x1 = ((self.b - 2 * self.b) + sqrt([self calculateD]))/ (2 * self.a);
    return self.x1;
}
-(double)calculateX2
{
    self.x2 = ((self.b - 2 * self.b) - sqrt([self calculateD]))/ (2 * self.a);
    return self.x2;
}

@end

Main.m:

#import <Foundation/Foundation.h>
#import "First.h"
#import "Second.h"
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        //This would be replaced by a user interface
        double firstA = 1;
        double firstB = 1;
        double secondA = 1;
        double secondB = 1;
        double secondC = 1;

        First *firstDegree = [[First alloc]initWithAValue:firstA andBValue:firstB];
        NSLog(@"The value of x for your first degree equation is: %.2f",[firstDegree calculate]);

        Second *secondDegree = [[Second alloc]initWithAValue:secondA andBValue:secondB andCValue:secondC];
        NSLog(@"D is: %.2f", [secondDegree calculateD]);
        NSLog(@"The values of x for your second degree equation are: %.2f and: %.2f",[secondDegree calculateX1],[secondDegree calculateX2]);
    }
    return 0;
}


texts:
I have following relationship schema:

class Participation
  belongs_to :toon
  belongs_to :person

  validates :role, :presence => true
end

class Toon
  has_many :participations
  has_many :people, :through => :participations
end

class Person
  has_many :participations
  has_many :toons, :through => :participations
end

I want to get people association related to toon, but filtered by role attribute value. I need something like toon.people_with_role('producer').

class Toon < ActiveRecord::Base
  has_many :participations
  has_many :people, :through => :participations

  def people_with_role(role)
    Participation.where(:toon_id => self, :role => role).map(&:person)
  end
end

It works, but I'm not sure that it is a best way to do it.


texts:
In getting accustomed to Clojure syntax, I wrote the following stutter function:

(defn doublelist [coll]
  (flatten (map (fn [x] [x x]) coll)))

(defn stutter [s]
  (clojure.string/join
    " " (doublelist (clojure.string/split s #" "))))

This duplicates every word in an input string:

(stutter "how are you?")
"how how are are you? you?"

The doublelist function bugs me. It seems that repeating items in a list should be possible without a call to flatten.

Any thoughts?


texts:
How can I pass data from database to my HTML template without putting PHP code in my HTML file.

Thanks.

This is my controller

public function index($aRequest)
{
    $oModel = new todoModel();
    $aTodoList = $oModel->getTodoList();
    return array('type' => 'view', 'view' => 'view/index.tpl', 'data' =>
    array('aTodoList' => $aTodoList));
}

my Model

public function getTodoList()
{
    $aTodoList = [];
    $this->oConnection->setAttribute(PDO::ATTR_ERRMODE,
    PDO::ERRMODE_EXCEPTION);

    $sQuery = 'SELECT * FROM t_todolist';
    foreach ($this->oConnection->query($sQuery) as $aTodo) {
        array_push($aTodoList, array(
            'sequence'    => $aTodo['sequence'],
            'todo'     => $aTodo['todo']
        ));
    }
    print_r($aTodoList);
    return $aTodoList;
}

my tpl -(this is working but it has php code inside)

<?php
foreach ($aTodoList as $aTodo) {
?>

<?php echo $aTodo['todo'];?>  update delete

<?php
}
?>

<button id="todo_create">create</button>


texts: Parsing website info with a database and web service

texts:
I have to make project for school in C# which has to use database and web service. I have made a program which starts a web service and gets a function from there which is used for connecting to a website. I am using HTML Agility Pack for parsing info from that website. Website info is then written in textbox and stored in database.

Here is one function from project, and the rest is here.

    public void HtmlParser()
    {
        Encoding enc = Encoding.UTF8;

        HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();

        htmlDoc.Load(client.Request(), enc);

        HtmlNode root = htmlDoc.DocumentNode;
        HtmlNodeCollection jobNode = root.SelectNodes("//div[@class='jobBox']");
        HtmlNodeCollection headerNode = root.SelectNodes("//div[@class='jobBox']/h1");
        HtmlNodeCollection contentNode = root.SelectNodes("//div[@class='jobBox']/div[@class='content']");
        HtmlNodeCollection linkNode = root.SelectNodes("//div[@class='jobBox']/a");

        jobs = new List<string>();
        headers = new List<string>();
        content = new List<string>();
        links = new List<string>();
        full_links = new List<Uri>();

        foreach (HtmlNode node in jobNode)
        {
            jobs.Add(node.InnerText);
        }
        foreach (HtmlNode node in headerNode)
        {
            headers.Add(node.InnerText.Trim());
        }
        foreach (HtmlNode node in contentNode)
        {
            content.Add(node.InnerText.Trim());
        }

        foreach (HtmlNode node in linkNode)
        {
            links.Add(node.GetAttributeValue("href", null).Trim());
            Uri temp = new Uri(link + node.GetAttributeValue("href", null).Trim());
            full_links.Add(temp);
        }

        htmlDoc.Save("file.htm", enc);

        StringParser();
    }

Some variables are in Croatian, so don't get confused. I am looking for helpful reviews and tips on how I can make my code better.