texts:
I wrote a Python program that draws the Mandelbrot set fractal. However, the program is very slow. I would appreciate any feedback on the program, but I would especially appreciate feedback on how to improve the performance of my program.

from PIL import Image, ImageDraw
import numpy as np

def FractalFunc(x, c):
    return (x * x) + c

def IterateFractal(c, iterateMax=100):
    z = 0
    last = np.nan
    for i in range(iterateMax):
        # c = FractalFunc(c, (.05+.5j)) # in case I want to create the Julia set
        z = FractalFunc(z,c)
        # if (np.abs(c) > 2):
        if (np.abs(z) > 2):
            last = i
            break
    return last

def QuickFractal(width=200, height=200, amin=-1.5, amax=1.5, bmin=-1.5, bmax=1.5,
            iterateMax=100, filename="blah.png"):
    (w, h, iMax, iterationValues, histogram) = Fractal(width, height, amin, amax, bmin, bmax, iterateMax)
    iFractal = DrawFractal(w, h, iMax, iterationValues, histogram)
    iFractal.show()
    iFractal.save(filename)

def ShowFractal(frac, filename="test.png"):
    (w, h, iMax, iterationValues, histogram) = frac
    iFractal = DrawFractal(w, h, iMax, iterationValues, histogram)
    iFractal.show()
    iFractal.save(filename)

def Fractal(width=200, height=200, amin=-1.5, amax=1.5, bmin=-1.5, bmax=1.5,
            iterateMax=100):
    aStep = (amax - amin) / (width)
    bStep = (bmax - bmin) / (height)
    """compute iteration values"""
    iterationValues = np.zeros((width, height))
    histogram = np.zeros(iterateMax)
    a = amin
    for x in range(width):
        b = bmin
        for y in range(height):
            c = np.complex(a,b)
            i = IterateFractal(c, iterateMax)
            iterationValues[x][y] = i
            if not(np.isnan(i)):
                histogram[i] = histogram[i] + 1
            b = b + bStep
        a = a + aStep
    return (width, height, iterateMax, iterationValues, histogram)

def DrawFractal(width, height, iterateMax, iterationValues, histogram):
    hue = np.zeros(iterateMax)
    hue[0] = histogram[0] / sum(histogram)
    image = Image.new("RGB", (width, height))
    for i in range(1, iterateMax):
        hue[i] = hue[i-1] + (histogram[i] / sum(histogram))
    """second pass to draw the values"""
    for x in range(width):
        for y in range(height):
            i_count = iterationValues[x,y]
            colorPixel = FractalColor(i_count, iterateMax, hue)
            image.putpixel((x,y), colorPixel)
    return image

def FractalColor(iterate, maxIt, hues):
    if np.isnan(iterate):
        return (0,0,0)
    else:
        grad_point_1 = np.array((0, 0, 255))
        grad_point_2 = np.array((255, 255, 255))
        grad_point_3 = np.array((0, 0, 255))
        hue_mod = (iterate % 100) / 100
        if (0 <= hue_mod < (.5)):
            delta = grad_point_2 - grad_point_1
            start = grad_point_1
        if ((.5) <= hue_mod < (1)):
            delta = grad_point_3 - grad_point_2
            start = grad_point_2
        scalar = ((hue_mod * 100) % (100 / 2))/30
        arr = np.floor(start + np.dot(scalar, delta))
        return tuple(arr.astype(int))

Example output:


texts: Given a string containing just parentheses, determine if the input string is valid

texts:
The task
is taken from leetcode

  Given a string containing just the characters '(', ')', '{', '}', '['
  and ']', determine if the input string is valid.

  An input string is valid if:

  Open brackets must be closed by the same type of brackets.
  Open brackets must be closed in the correct order.
  Note that an empty string is also considered valid.

  Example 1:

Input: "()"

Output: true

  Example 2:

Input: "()[]{}"

Output: true

  Example 3:

Input: "(]"

Output: false

  Example 4:

Input: "([)]"

Output: false

  Example 5:

Input: "{[]}"

Output: true

My functional solution

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = s => {
  const par = {
      "(": ")",
      "{": "}",
      "[": "]",
    };
  const rep = [];
  return [...s].every(x => par[x]
                      ? rep.push(par[x])
                      : rep.pop() === x) && !rep.length;
};

My imperative soltion

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid2 = s => {
  const par = {
      "(": ")",
      "{": "}",
      "[": "]",
    };
  const rep = [];
  for (let i = 0; i < s.length; i++) {
    if (par[s[i]]) {
      rep.push(par[s[i]]);
    } else {
      if (rep.pop() !== s[i]) {
        return false;
      }
    }
  }
  return rep.length === 0;
};


texts:
I have two different folders.

In one folder, I have files that will be exported to a remote site via FTP.

In a second folder, I have .dat files that will be processed by a ftp client program that I have. Each .dat file contains basic information that my ftp program needs to process a request.

I needed to create a bunch of dummy files and dummy requests to test my ftp program. I decided to create these dummy files with Powershell.

I know almost nothing about Powershell, so even the most basic advice would be helpful.

This is all inside a Powershell script that can be run from the Powershell ISE.

$export_src_base = "D:\csv_exports"
$export_src_dir = "$export_src_base\test"
$queue_dir = "D:\FTP\Queue"

# Create the export source directory if it does not exist.
if (-not(Test-Path $export_src_dir)){
    New-Item -ItemType directory -Path $export_src_dir
}

for ($i=1; $i -le 100; $i++){
    # Create 100 dummy files if they do not exist.
    $file = "$i.txt"
    $filepath = "$export_src_dir\$file"

    if (-not(Test-Path $filepath)){
        New-Item -ItemType file -Path $filepath -Value $i
    }

    # Create 100 dummy requests if they do not exist.
    $queue_file = "$i.dat"
    $queue_filepath = "$queue_dir\$queue_file"

$value = @"
[Item]
SrcFileName=$filepath
DestFileName=$file
FTPSite=Site1
DestPath=Temp\Testing
Sent=0
ErrorCount=0
LastTriedTime=
"@

    if (-not(Test-Path $queue_filepath)){
        New-Item -ItemType file -Path $queue_filepath -Value $value
    }

}


texts: Java Client with ElasticSearch SearchQuery if the value of field is not empty

texts:
I developed a java Client to interrogate with elasticsearch.

I want to pass in my method a java bean (with many attributes) as a parameter, and I want also that my query apply search just on field that are not empty

I used it this way in java but I'm wanting to do it well (with best practices) to replace IF.

If there is any solution from elasticsearch or java client for elasticsearch, please let me know.

public void chercherParplusisuersCrieres(EsClient esClient) {
    BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

    boolQuery.must(QueryBuilders.matchQuery("_all", esClient.getMotCle()));
    if (!esClient.getComplementAdresse().isEmpty()) {
        boolQuery.must(QueryBuilders.matchQuery("Complement_adresse", esClient.getComplementAdresse()));
    }
    if (!esClient.getNom().isEmpty()) {
        boolQuery.must(QueryBuilders.matchQuery("Nom", esClient.getNom()));
    }
    if (!esClient.getPrenom().isEmpty()) {
        boolQuery.must(QueryBuilders.matchQuery("Prenom", esClient.getPrenom()));
    }
    if (!esClient.getLibelleQuartier().isEmpty()) {
        boolQuery.must(QueryBuilders.matchPhrasePrefixQuery("Libille_quartier", esClient.getLibelleQuartier()));
    }
    SearchRequestBuilder builder = this.client.prepareSearch("index").setTypes("index_type")
            .setQuery(boolQuery);
    System.out.println(builder);
    SearchResponse response = builder.get();
    List<EsClient> esClientList = new ArrayList<EsClient>();
    List<String> listColumns = Arrays.asList("Complement_adresse", "Nom", "Prenom", "Libille_quartier",
            "Date_operation");
    // get all Hits of response
    SearchHits searchHits = response.getHits();

    // searchHits.getHits() instead of searchHits.getTotalHist() beacause eclipse
    // support just 10 results
    for (int i = 0; i < searchHits.getHits().length - 1; i++) {
        esClient = new EsClient();
        esClient.setComplementAdresse((String) searchHits.getAt(i).getSourceAsMap().get(listColumns.get(0)));
        esClient.setNom((String) searchHits.getAt(i).getSourceAsMap().get(listColumns.get(1)));
        esClient.setLibelleQuartier((String) searchHits.getAt(i).getSourceAsMap().get(listColumns.get(2)));

        esClientList.add(esClient);
    }
    System.out.println(esClientList);

}


texts: Input data from file, calculating average by a function

texts:
I want to thank you guys firstly for your previous comments and feedback. Really appreciate it. I am learning C with school at the moment, but I plan to be "fluent" in C at the end of august of this year.

For school I have to write the following program:

Open up a file. The file is a *.txt one. It consists of 32 numbers. The first number corresponds to the number of tests distributed under the students. The second number is saying how many have returned the test. The other 30 numbers could be seperated into a 5 by 6 table. There were 6 question with each 5 possible answers. the numbers represent how many students have chosen the answer. The file is posted at the end of this post.

Now I have to open this file and making a display like this:

number of passed tests: 20
Number of returned tests: 19
Response is 95%.
                  A      B      C      D    E    grade     passed
question 1   2      2      2      2    2     2.4         yes
question 2   2      2      2      2    2     2.4         yes
question 3   2      2      2      2    2     2.4         yes
question 4   2      2      2      2    2     2.4         yes
question 5   2      2      2      2    2     2.4         yes
question 6   2      2      2      2    2     2.4         yes

Also note that the "comment" has three options; fail if grade<3.0 , warning if grade<3.5 and pass if higher than 3.5.
The code I Have written is like this :

#include <stdio.h>
#define RIJ 6
#define KOLOM 5

int invoer[RIJ][KOLOM] , rij, kolom;
float ingeleverd ;

float functie(int* i ) ;
int main(void)
{

float uitgereikt=0  , percentage ;
char bestandpad[100]= "" ;

FILE *inputbestand;
printf("Dit programma verwerkt de data uit verschillende enquetes.\n");
printf("\n");
printf("Voer de locatie van het bestand in.\n");
scanf("%s", &bestandpad);
inputbestand=fopen(bestandpad, "r" );

    if (inputbestand == NULL)
        { printf("Bestand niet gevonden.");
            return 0;
        }

fscanf(inputbestand, "%f", &uitgereikt);
fscanf(inputbestand, "%f", &ingeleverd);
percentage = (ingeleverd/uitgereikt) *100 ;
//------- overige data inlezen in een array van 5 bij 6.

    for (rij=0; rij<RIJ; rij++)
       {
           for (kolom=0; kolom<KOLOM ; kolom++)
           {
                   fscanf(inputbestand, "%d", &invoer[rij][kolom]);
           }
       }
fclose(inputbestand);

printf("Aantal uitgereikte evaluaties: %0.f\n" , uitgereikt);
printf("Aantal ingeleverde evaluaties: %0.f\n" , ingeleverd);
printf("Response is: %.1f %% \n\n" , percentage);
printf("   \t  A\t B \t C \t D \t E \t cijfer \t opmerking\n\n");

            for (rij=0; rij<RIJ; rij++)
            {
                    printf("vraag %d   " ,rij+1);

                for (kolom=0; kolom<KOLOM ; kolom++)
                {
                    printf("%d       ", invoer[rij][kolom]);

                    if (kolom==KOLOM-1) {
                                            printf("%c \n", functie(invoer[rij]));
                                        }

                }
            }
}
float functie(int* i )
{
    int a ;
    float gem, totaal;

    for (a=0; a<5 ; a++)
    {totaal= totaal+ ( i[a] * (a+1)  ) ;}

    gem =  totaal/ingeleverd ;

    if      (gem<3.0)      {printf("%.1f \t \t Voldoet niet\n", gem);}
    else if (gem<3.5)      {printf("%.1f \t \t opmerking\n", gem);}
    else if (gem>3.5)      {printf("%.1f \t \t Voldoet\n", gem);}
  //  return  gem ;
}

It is working completely. I have one minor bug though. the results are not aligned properly. What do you guys think ? Except the bad indenting... I am also very sorry it is in Dutch. But I think you guys will understand alright..

the inputfile is like this:

    20
    19
    1
    2
    4
    5
    7
    0
    1
    8
    7
    3
    8
    5
    4
    2
    0
    2
    2
    4
    11
    0
    2
    3
    3
    5
    6
    0
    0
    4
    12
    3


texts: Subprocess CSV validator and multiprocessing on Python

texts:
This Python script takes a directory of CSV files and calls a Scala script which tests whether a file's contents match a given regular expression. The link to this Scala script can be found in the 3rd line.

That script takes a single file as argument, hence my creation of this Python script to feed it an entire directory worth of files, while also utilizing the maximum possible amount of CPU power.

Do you see any issues or potential improvements in my code?

"""
Command line API to CSV validator using Scala implementation from:
http://digital-preservation.github.io/csv-validator/#toc7
"""

PATH_TO_VALIDATOR = r"C:\prog\csv\csv-validator-cmd-1.2-RC2\bin\validate.bat"
PATH_TO_CSV_FOLDER = r"C:\prog\csv\CSVFiles"
PATH_TO_CSV_SCHEMA = r"C:\prog\csv\ocr-schema.csvs"

# Set defaults
CSV_ENCODING = "windows-1252"
CSV_SCHEMA_ENCODING = "UTF-8"

def open_csv(CSV_LIST):
    import subprocess

    # To be used to display a simple progress indicator
    TOTAL_FILE_COUNT = len(CSV_LIST)
    current_file_count = 1

    with open("output.txt", 'w') as output:
        for filename in CSV_LIST:
            print("Processing file " + str(current_file_count) + "/" + str(TOTAL_FILE_COUNT))

            output.write(filename + ': ')
            validator = subprocess.Popen(
                [PATH_TO_VALIDATOR, PATH_TO_CSV_FOLDER + "/" + filename, PATH_TO_CSV_SCHEMA, "--csv-encoding",
                 CSV_ENCODING, "--csv-schema-encoding", CSV_SCHEMA_ENCODING, '--fail-fast', 'true'], stdout=subprocess.PIPE)
            result = validator.stdout.read()
            output.write(result.decode('windows-1252'))

            current_file_count += 1

# Split a list into n sublists of roughly equal size
def split_list(alist, wanted_parts=1):
    length = len(alist)
    return [alist[i * length // wanted_parts: (i + 1) * length // wanted_parts]
            for i in range(wanted_parts)]

if __name__ == '__main__':
    import argparse
    import multiprocessing
    import os

    parser = argparse.ArgumentParser(description="Command line API to Scala CSV validator")
    parser.add_argument('-pv', '--PATH_TO_VALIDATOR', help="Specify the path to csv-validator-cmd/bin/validator.bat",
                        required=True)
    parser.add_argument('-pf', '--PATH_TO_CSV_FOLDER', help="Specify the path to the folder containing the csv files "
                                                            "you want to validate", required=True)
    parser.add_argument('-ps', '--PATH_TO_CSV_SCHEMA', help="Specify the path to CSV schema you want to use to "
                                                            "validate the given files", required=True)

    parser.add_argument('-cenc', '--CSV_ENCODING', help="Optional parameter to specify the encoding used by the CSV "
                                                        "files. Choose UTF-8 or windows-1252. Default windows-1252")
    parser.add_argument('-csenc', '--CSV_SCHEMA_ENCODING', help="Optional parameter to specify the encoding used by "
                                                                "the CSV Schema. Choose UTF-8 or windows-1252. "
                                                                "Default UTF-8")

    args = vars(parser.parse_args())

    if args['CSV_ENCODING'] is not None:
        CSV_ENCODING = args['CSV_ENCODING']

    if args['CSV_SCHEMA_ENCODING'] is not None:
        CSV_SCHEMA_ENCODING = args['CSV_SCHEMA_ENCODING']

    PATH_TO_VALIDATOR = args["PATH_TO_VALIDATOR"]
    PATH_TO_CSV_SCHEMA = args["PATH_TO_CSV_SCHEMA"]
    PATH_TO_CSV_FOLDER = args["PATH_TO_CSV_FOLDER"]

    CPU_COUNT = multiprocessing.cpu_count()

    split_csv_directory = split_list(os.listdir(args["PATH_TO_CSV_FOLDER"]), wanted_parts=CPU_COUNT)

    # Spawn a Process for each CPU on the system
    for csv_list in split_csv_directory:
        p = multiprocessing.Process(target=open_csv, args=(csv_list,))
        p.start()


texts: Iterating over a range of integer ranges in Java

texts:
My use case is this:

RangeDemo.java:

package net.coderodde.util;

public class RangeDemo {

    public static void main(String[] args) {
        for (Integer i : new Ranges(new Range(-9, 0),
                                    new Range(3, 5),
                                    new Range(15, 10),
                                    new Range(11, 11),
                                    new Range(16, 17))) {
            System.out.print(i + " ");
        }
    }
}

... which gives me:

-9 -8 -7 -6 -5 -4 -3 -2 -1 3 4 10 11 12 13 14 16

My implementation is this:

Range.java:

package net.coderodde.util;

/**
 * This class implements a range of integers.
 *
 * @author Rodion "rodde" EfremoB.
 * @version 1.6 (Jun 10, 2019)
 */
public final class Range {

    private final int fromIndex;
    private final int toIndex;

    public Range(final int fromIndex, final int toIndex) {
        this.fromIndex = Math.min(fromIndex, toIndex);
        this.toIndex   = Math.max(fromIndex, toIndex);
    }

    int get(int index) {
        return fromIndex + index;
    }

    int size() {
        return toIndex - fromIndex;
    }
}

Ranges.java:

package net.coderodde.util;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * This class implements an integer iterator over a range of ranges.
 *
 * @author rodde
 */
public final class Ranges implements Iterable<Integer> {

    /**
     * This static inner class implements the actual iterator.
     */
    private static final class RangeIterator implements Iterator<Integer> {

        /**
         * Holds the actual ranges.
         */
        private final Range[] ranges;

        /**
         * The index of the current range.
         */
        private int currentRangeIndex;

        /**
         * The current index within the current range.
         */
        private int currentElementIndex;

        /**
         * The total number of integers to iterate.
         */
        private final int globalSize;

        /**
         * The global number of integers already iterated.
         */
        private int globalIndex;

        private RangeIterator(Range[] ranges) {
            this.ranges = ranges;
            this.globalSize = countGlobalSize();

        }

        @Override
        public boolean hasNext() {
            return globalIndex < globalSize;
        }

        @Override
        public Integer next() {
            if (!hasNext()) {
                throw new NoSuchElementException("Nothing to iterate.");
            }

            while (currentElementIndex == ranges[currentRangeIndex].size()) {
                currentRangeIndex++;
                currentElementIndex = 0;
            }

            globalIndex++;
            return ranges[currentRangeIndex].get(currentElementIndex++);
        }

        private int countGlobalSize() {
            int globalSize = 0;

            for (Range r : ranges) {
                globalSize += r.size();
            }

            return globalSize;
        }
    }

    private final Range[] ranges;

    public Ranges(Range... ranges) {
        this.ranges = Objects.requireNonNull(ranges);
    }

    @Override
    public Iterator<Integer> iterator() {
        return new RangeIterator(ranges);
    }

    @Override
    public void forEach(Consumer<? super Integer> action) {
        RangeIterator rangeIterator = new RangeIterator(this.ranges);
        rangeIterator.forEachRemaining(action);
    }
}


texts: Replace an element of a List with a concrete Id

texts:
I want to replace an object of a List with another one. To find the item to replace I need to check the field id of the object to find what item is the same.

public void changeItemInformation(@NonNull Suggestion suggestion) {
    if (mSuggestions != null) {
        int itemChanged = -1;
        int index = -1;
        for (Suggestion suggestionItem : mSuggestions) {
            index++;
            if(suggestionItem.getId() == suggestion.getId()){
                itemChanged = index;
                break;
            }
        }
        if (itemChanged != -1) {
            mSuggestions.set(itemChanged, suggestion);
            notifyItemChanged(itemChanged);
        }
    }
}

mSuggestions is the list of Suggestions.
suggestion is the new item to replace the old one.
notifyItemChanged() is an Android method to notify a RecyclerView that an element changed.

Is there a better way to do this? There aren't any perform problems, the list always has a maximum of 100 elements.


texts: Entity Framework with multiple connections open?

texts:
I'm learning Entity Framework and I'm wondering if this code is the proper way of doing this.  Basically this is my attempt at refactoring a very long controller in ASP.Net MVC 4.  I'm using Entity Framework 5 as well.

What I did was I separated out some code into a more common method (buildUpdatedAnswerDetailRecord).

Notice in my parent function I have a connection open because I'm doing other DB related operations (population of data into properties).  But then in the buildUpdatedAnswerDetailRecord method I'm opening another connection and then passing back a AnswerDetail.

Is this the right way to do this or should I have just kept 1 connection open and just duplicated code?

using (var db = new LEAP_Professional_DAL.DAL.LEAPEntitiesDAL())
{

//local variable of a AnswerDetail
AnswerDetail adItem;

//Doing a lot of other Database work (filling other properties)
....

adItem = buildUpdatedAnswerDetailRecord(evaluation.IsLeader, item, backButtonItem.AnswerDetailKey);
db.Entry(adItem).State = EntityState.Modified;

....
//Doing a lot of other Database work (filling other properties)

}

    private AnswerDetail buildUpdatedAnswerDetailRecord(Boolean isLeader, EvaluationObject item, int? detailKey)
    {
        try
        {
            AnswerDetail buildAdItem;
            using (var db = new DAL.DAL.EntitiesDAL())
            {
                buildAdItem = db.AnswerDetails.Find(detailKey);
                if (buildAdItem != null)
                {
                    ((IObjectContextAdapter)db).ObjectContext.Detach(buildAdItem);
                    if (isLeader == true)
                    {
                        buildAdItem.Comment = item.LeaderComment;
                        buildAdItem.AnswerOptionKey = item.LeaderAnswerOptionKey.Value;
                        buildAdItem.UpdatedBy = userName;
                        buildAdItem.UpdateStamp = DateTime.Now;
                    }
                    else
                    {
                        buildAdItem.Comment = item.TeacherComment;
                        buildAdItem.AnswerOptionKey = item.TeacherAnswerOptionKey.Value;
                        buildAdItem.UpdatedBy = userName;
                        buildAdItem.UpdateStamp = DateTime.Now;
                    }

                }
            }
            return buildAdItem;
        }
        catch (Exception ex)
        {
            throw new Exception("buildUpdatedAnswerDetailRecord Error Occured: " + ex.Message.ToString());
        }
    }


texts:
I was wondering if you could review the following code I've written as a polyfill for the placeholder attribute in HTML5?

The object of the polyfill is to replicate the functionality of the placeholder attribute. In effect, the polyfill is supposed to do the following:

Default text to be shown.
On Focus: Erase the default text.
On Focus Out: Put in default text if nothing has been entered

Dependancies:

jQuery

var Utils = Utils || {};

Utils = (function (window, $) {

    var _c, _private, _public;

    _private = {

        /**
         * @event
         * @param e The event object.
         */
        'handleFocusIn': function (e) {
            var $target = $(e.currentTarget);
            if($target.val() === $target.attr('placeholder')) {
                $target.val('');
            }
            $target
                .unbind('focusin')
                .bind('focusout', _private.handleFocusOut);
        },

        /**
         * @event
         * @param e The event object.
         */
        'handleFocusOut': function (e) {
            var $target = $(e.currentTarget);
            if($target.val() === '') {
                $target.val($target.attr('placeholder'));
            }
            $target
                .unbind('focusout')
                .bind('focusin', _private.handleFocusIn);
        }
    };

    _public = {
        /**
         * @function
         * @description
         * A poly-fill for the placeholder attribute.
         */
        'supportsPlaceholderAttr': function (enableFallback) {
            var placeHolderSupported = false;

            //If enableFallback is either undefined or not a Boolean, set it to false
            if((typeof enableFallback === 'undefined') || !(enableFallback instanceof Boolean)) {
                enableFallback = false;
            }

            //if placeholder is supported, no reason to continue on
            if ('placeholder' in document.createElement("input")) {
                return placeHolderSupported = true;
            }

            if (!placeHolderSupported && !!enableFallback) {
                var $inputEle;
                $('input')
                    .each( function(index, ele) {
                        $inputEle = $(ele);
                        if($inputEle.attr('placeholder')) {
                            $inputEle
                                .val($inputEle.attr('placeholder'))
                                .bind('focusin', _private.handleFocusIn);
                        }
                    });
            }
        }
    };

    return _public;

}(window, jQuery));


texts: A Merge Sort implementation for efficiency

texts:
This is my version of mergesort.
# mergesort

def merge(items, low, mid, high):
    left = [items[i] for i in range(low, mid + 1)]
    right = [items[i] for i in range(mid + 1, high + 1)]
    left.append(4444444444444444444444)
    right.append(4444444444444444444444)

    i = 0
    j = 0
    for k in range(low, high + 1):
        if left[i] < right[j]:
            items[k] = left[i]
            i += 1
        else:
            items[k] = right[j]
            j += 1

def mergesort(items,low, high):
    mid = int(low + (high - low) / 2)
    if low < high:
        mergesort(items, low, mid)
        mergesort(items, mid + 1, high)
        merge(items, low, mid, high)

if __name__ == "__main__":
    a = [6, 5, 4, 3, 2, 1]
    print(mergesort(a, 0, len(a) - 1))

I ran a test with input size of 1000000 in reverse order with a step of 1 i.e range(int(1e6), 1, -1) or range(1000000, 1, -1)  and got the following results
6999991 function calls (4999995 primitive calls) in 9.925 seconds

   Ordered by: internal time
   List reduced from 9 to 8 due to restriction <8>

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
   999998    6.446    0.000    8.190    0.000 test.py:3(merge)
1999997/1    1.735    0.000    9.925    9.925 test.py:19(mergesort)
   999998    0.821    0.000    0.821    0.000 test.py:4(<listcomp>)
   999998    0.740    0.000    0.740    0.000 test.py:5(<listcomp>)
  1999996    0.183    0.000    0.183    0.000 {method 'append' of 'list' objects}
        1    0.000    0.000    9.925    9.925 {built-in method builtins.exec}
        1    0.000    0.000    9.925    9.925 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 {built-in method builtins.len}

I would love to optimize the code and if possible, eliminate the copies.


texts:
I was wondering if it is better to use:

    double onJupiter() {
     return AgeInSeconds / (jupiterOrbitalInEarthYears * ageInEarthSeconds);
    }

    double onMars() {
     return inputAgeInSeconds / (marsOrbitalInEarthYears * ageInEarthSeconds);
 }

Or:

  double onJupiter() {
        return onEarth() / JUPITER_ORBIT_RATIO;
    }

  double onMars() {
    return onEarth() / MARS_ORBIT_RATIO;
  }

In the second option, notice I called the onEarth() method twice. Does calling onEarth() create a brand new Stack (a bit like in recursion), hence it is not good to use? Because if I have a bunch of methods like onMars(), onMercury etc and they all call onEarth(), then would I end up creating a lot of new stacks?

Here are the Java classes in question:

Class 1:

class SpaceAge {

    private final double AgeInSeconds;
    private static final double ageInEarthSeconds = 31557600;
    private static final double marsOrbitalInEarthYears = 0.2408467;
    private static final double jupiterOrbitalInEarthYears = 11.862615;

    SpaceAge(double seconds) {
        this.AgeInSeconds = seconds;
    }

    double getSeconds() {
        return AgeInSeconds;
    }

    double onEarth() {
        return AgeInSeconds / ageInEarthSeconds;
    }

    double onJupiter() {
        return AgeInSeconds / (jupiterOrbitalInEarthYears * ageInEarthSeconds);
    }

    double onMars() {
        return AgeInSeconds / (marsOrbital * ageInEarthSeconds);
    }

}

Class 2:

class SpaceAge {

    private static final double EARTH_YR_IN_SECS = 31557600;
    private static final double MARS_ORBIT_RATIO = 1.8808158;
    private static final double JUPITER_ORBIT_RATIO = 11.862615;

    private final double ageInSeconds;

    SpaceAge(final double seconds) {
        this.ageInSeconds = seconds;
    }

    double getSeconds() {
        return this.ageInSeconds;
    }

    double onEarth() {
        return this.ageInSeconds / EARTH_YR_IN_SECS;
    }

    double onJupiter() {
        return onEarth() / JUPITER_ORBIT_RATIO;
    }

    double onMars() {
        return onEarth() / MARS_ORBIT_RATIO;
    }
}


texts: Varying Parameter Names in Method Overloads

texts:
Probably a dumb question but just can't seem to make a decision here.

I'm building a C# class library that I intend for other developers to use. Let's say one of these classes contains a method that accesses a remote resource and maps it to an object:

public class FooClient
{
    public async Task<Foo> ShowAsync(string name, ...)
    {
        return await DoStuffAsync(name);
    }
}

Where name identifies this remote resource. Let's also say that this resource can be identified by a numerical id, and that I can pass id.ToString() as name to this method and retrieve the same resource. So, I want an overload:

public class FooClient
{
    public async Task<Foo> ShowAsync(string name, ...)
    {
        return await DoStuffAsync(name);
    }
    public Task<Foo> ShowAsync(long id, ...)
    {
        return ShowAsync(id.ToString(), ...);
    }
}

According to the Microsoft docs, I should avoid arbitrarily varying parameter names, so I'm tempted to do something like this:

public class FooClient
{
    public async Task<Foo> ShowAsync(string foo, ...)
    {
        return await DoStuffAsync(foo);
    }
    public Task<Foo> ShowAsync(long foo, ...)
    {
        return ShowAsync(foo.ToString(), ...);
    }
}

But I'm afraid that, in this case, it would be more descriptive to have different names for the parameters, even though they identify the same resource. What should I do?


texts: Longest string in a vector — two implementations

texts:
I was given this piece of code, which calculates the length of the longest string in a vector of strings:

static size_t max_line_length(std::vector<std::string> &lines) {
    size_t max = 0;
    for (auto it = lines.begin(); it != lines.end(); it++) {
        if (it->length() > max) {
            max = it->length();
        }
    }
    return max;
}

I am new to C++ with a significant background in Java. If I would write such a function myself, I would come up with something like:

static size_t max_line_length(std::vector<std::string> lines) {
    size_t max = 0;
    for (auto line : lines) {
        if (line.length() > max) {
            max = line.length();
        }
    }
    return max;
}

The difference is in the use of pointers, and the way in iterating the strings.

Is there a significant performance difference between these implementations, or are there best practices involved in this?


texts:
My concern is speed, since this may be used in an e-commerce website I want it to be as quick as possible. Where can I improve?

def get_queryset(self):
    search_terms = self.request.GET.getlist('search', None)

    if not search_terms:
        return []

    # removing trailing slash on restangular calls
    search_terms[0] = search_terms[0].lower().replace('/', '')

    terms = [term.split(" ") for term in search_terms][0]

    # Query that will go through each item to see if their name or description match contain the search terms
    results = reduce(operator.or_,
                     (Item.objects.filter
                      (Q(name__icontains=term) | Q(description__icontains=term))
                      for term in terms))

    # Using enumerate so I can get the index, storing index at end of list for future reference
    # Concats the item name and the item description into one list, using that for the items weight in the result
    results_split = [list(set(item.name.lower().split() + item.description.lower().split() + list((index,))))
                     for index, item in enumerate(results)]

    # Builds weight for each term
    # Example: The search has 3 terms, Red, Shoes, Pants
    # Red would have a weight of 3 since it is the first word, shoes would be 2 and pants would be 1
    query_with_weights = [(term, len(search_terms[0].split()) - search_terms[0].split().index(term))
                          for term in terms]

    # This section will go through and weigh each item based on name and description weight.
    # This may be problematic if the description uses the key word multiple times.
    #  It could result in things being weighed incorrectly. See the example below for more details.
    # Example 2: 'red pants' is the query.
    # We have, in no particular order, a red shoe item, a blue pants item, a red pants item, a red swim trunks item.
    # Each items description is sweet {{ item.name }} bro
    # The resulting weight would be Red: 2, Pants: 1
    # However, the returned result would be, in this order, [Red Pants, Red Shoe, Red Swim Trunks, Blue Pants]
    get_weight = lambda x: ([weight for y, weight in query_with_weights if y == x] or [0])[0]
    sorted_results = sorted([(item, sum([(get_weight(term)) for term in item])) for item in results_split],
                            key=lambda lst: lst[1], reverse=True)

    # Using the index stored from before I am able to access the original results list in order and
    #  create a new list that is now sorted based on the weight of each item in the search.
    # I am planning to expand this purely for educational purposes to include tags in the weighing and filtering process.
    all_results = [results[result[0][result[0].index(term)]] for result in sorted_results for term in result[0] if
                    type(term) is int]

    # Gets the top level item for each sub item that hit in the results.
    #   If multiple sub items FK back to the a single master item we want to only display that master item once.
    top_level_sorted = list(set([Item.objects.get(id=item.get_top_level_item().id)
                                    for item in all_results if item.is_variant]))
    return top_level_sorted


texts: Avoid global variable for callback function called by function with no arguments

texts:
My website has multiple pages that use the Google Maps api. Each page uses a different part of the api (e.g. autocomplete, displaying markers etc). However, every page needs to call the initMap() function for the api to be initialized. The logic that calls initMap() is controlled by google and it cannot take parameters.
maps.js
function initMap() {
  const mapOptions = {
    center: {lat: 0, lng: 0},
    zoom: 7
  };
  window.map = new google.maps.Map(document.getElementById("map"), mapOptions);

  if (typeof callback !== 'undefined') {
    callback(); // defined above html link to maps.js
  }
}

Instead of writing out a different initMap() function for every page, I opted to have it in one .js file which is linked to every page. After initializing the map, the function executes a callback function which is defined in each page's corresponding .js file.
index.js
function autocomplete() {
    var input = document.getElementById('address');
    new google.maps.places.Autocomplete(input);
}

As initMap() cannot take parameters, I had to define the callback function's name using a cross-script global variable before maps.js is linked. This variable is different on every page depending what function needs to be run in initMap() after the map is initialized.
<script type="text/javascript" src="js/index.js"></script>
<script> var callback = autocomplete </script> <!-- global variable, defines the callback function (in index.js) to initMap()(in maps.js) -->
<script type="text/javascript" src="js/maps.js"></script>

Is there a cleaner way to accomplish this?


texts: JavaScript switch statement to make an AJAX call

texts:
I have a button group that looks like this:

The user selects one of the options and they can search for a person based on that criteria.

I wrote a switch statement that populates the URL to make the ajax call to  get the data based on the option selected.

However, the down side of this is that every time an option is added or removed, I have to modify the corresponding JavaScript.

Should I re-factor the code to use data- attributes on the a tags, that contain the URL to use?

Username

Last Name

Student ID

Or is that considered bad mojo?

What I have working:

HTML

Username

Last Name

Student ID

JS

    // All of the list items in the drop down
    var $searchOptions = $('#btGo-dropdown li');
    $searchOptions.click(function (e) {
        var searchBy = '';

        // find all of the child links, which are
        // the options themselves
        var $lis = $searchOptions.find('a');

        // remove the active class, if exists
        $lis.filter('.active').removeClass('active');

        // add the active class to show the criteria selected
        var clickedOptionId = e.target.id;
        $('#' + clickedOptionId).addClass('active');

        // depending on the option selected, populate
        // searchBy with the URL to make the ajax call to
        switch (clickedOptionId) {
            case "btUsername":
                searchBy = 'SearchByUsername';
                break;
            case "btLastName":
                searchBy = 'SearchByLastName';
                break;
            case "btStudentID":
                searchBy = 'SearchByStudentID';
                break;
            default:
        }

        // create an object that abstracts the search data
        var search = {
            url: searchBy,
            data: { criteria: $search.attr('value') }
        };

        // make the call to the controller and get the raw Json
        var itemModels = $.ajax({
            url: search.url,
            type: "GET",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: search.data,
            async: false
        }).responseText;

        // Use knockout.js to bind the information to the page
        viewModel.rebindSearchItems(itemModels);

    });


texts: Determine if two arrays are a rotated version of each other

texts:
Following algorithm has time complexity \$O(N)\$ and space complexity \$O(1)\$.

Any suggestions to improve this algorithm or any alternate approach suggestions?

public static boolean isRotatedVersion(int[] a, int[] b){
        //Check length of arrays
        if(a.length != b.length)
            return false;

        //Declare two pointers. One for each array
        int aPointer = 0;
        int bPointer = 0;

        //This flag will prevent us walking through the 2nd array in a loop only once
        //Helps avoid going into infinite walk loop
        boolean isFirstTimeWalk = true;

        //This loop will run from 0 to n of array 1
        while(aPointer < a.length){

            //If elements at position aPointer and bPointer are equal then incr both pointer
            // to move to the element in both array
            if(a[aPointer] == b[bPointer]){
                aPointer++;
                if(bPointer < b.length-1)
                    bPointer++;
                else{ //If reached end of second array then it reset pointer to 0 to rotate
                    //Once rotated done mark is1stTimeWalked to false so avoid future loops
                    isFirstTimeWalk = false;
                    bPointer = 0;
                }
            }else if(isFirstTimeWalk && bPointer < b.length-1){
                //Move bPointer until a match is found
                bPointer++;
            }else {
                return false;
            }
        }
        return true;
    }
}


texts: Is it possible to use switch case for more than one array.indexOf

texts:
I have some set of if conditions for a particular array using JavaScript.

activity is the array containing 10-12 items. This array is converted to a multiple select dropdown. Depending upon the value selected, I need to hide and show divs. I also need to set values of another input choice as "NA".

Here's the code written for the onchange of that multiple select dropdown.

activity = ["strategy session","sessions","virtual",...,"Other"]

if (activity.indexOf("strategy session") != -1) {
    $("#FoPStrategySession").show();
}

if (activity.indexOf("sessions") != -1) {
    $("#acprojectname").show();
    if (supportmodel == "Level") {
        $(".accombohide").hide();
        $("[title='Test']").val("NA");
        $("[title='Test2']").val("NA");
    }
}

if (activity.indexOf("virtual") != -1) {
    if (supportmodel == "Level") {
        $(".lvl3_consult").hide();
        $("[title='Test']").val("NA");
        $("[title='Test2']").val("NA");
    }
}

if (activity.indexOf("Other") != -1) {
    $("#acactivityother").show();
}

Is there any other way to efficiently write this code using switch case or any other method?


texts: Disabling child scaling, when parent scales with Math

texts:
I think this code is only simple math, but I'm posting it, because almost everyone fakes the scaling with unparenting, then parenting again.

Vector3 originalParentScale = new Vector3;
Vector3 originalScale = new Vector3;
void Awake(){
    originalScale = transform.localScale;
    originalParentScale = transform.parent.localScale;
}
void Update(){
    transform.localScale = (originalParentScale / transform.parent.localScale) * originalScale;
}

I think it can be even improved, so I would be happy if someone can improve it. It's challenge too, so happy programming :-)


texts: Terser syntax for first-class functions needing a context bound

texts:
I have the following function that looks up a mathematical operation that can be applied to a Numeric sequence based on a String

def getAction[T : Fractional]( op : String ) : Seq[T] => String =
  op match {
    case "add" => seq => seq.sum.toString
    case "product" => seq => seq.product.toString
    case "mean" => seq => {
      implicit def intToFractional(i : Int) =
        implicitly[Fractional[T]].fromInt(i);
      (seq.sum / seq.length).toString
    }
    case "sqrt" => seq => seq.map(i => math.sqrt(i.toDouble)).toString
  }

That works fine, except I would prefer to specify the type when applying the returned function rather than at the time or retrieval.

i.e. I want

getAction("sqrt")[Double](Seq(4.0))

rather than

getAction[Double]("sqrt")(Seq(4.0))

The only way I have found to do this is by defining a new class/trait with a generic context-bound apply.

abstract class Action {
  def apply[T : Fractional](seq : Seq[T]) : String
}

Edit: Replaced with whole class rather than just the method because compilable solution was wanted.

object Main extends App {
  import scala.math.Fractional
  import Fractional.Implicits._
  import scala.language.implicitConversions

  abstract class Action {
    def apply[T : Fractional](seq : Seq[T]) : String
  }

  def getAction( op : String ) : Action =
  op match {
    case "add" =>
      new Action {
        def apply[T : Fractional](seq : Seq[T]) = seq.sum.toString
      }
    case "product" =>
      new Action {
        def apply[T : Fractional](seq : Seq[T]) = seq.product.toString
      }
    case "mean" =>
      new Action {
        def apply[T : Fractional](seq : Seq[T])= {
          implicit def intToFractional(i : Int) =
            implicitly[Fractional[T]].fromInt(i);

          (seq.sum / seq.length).toString
        }
      }
    case "sqrt" =>
      new Action {
        def apply[T : Fractional](seq : Seq[T]) =
           seq.map(i => math.sqrt(i.toDouble)).toString
      }
  }

  def getAction_v1[T : Fractional]( op : String ) : Seq[T] => String =
    op match {
      case "add" => seq => seq.sum.toString
      case "product" => seq => seq.product.toString
      case "mean" => seq => {
        implicit def intToFractional(i : Int) =
          implicitly[Fractional[T]].fromInt(i);
        (seq.sum / seq.length).toString
        }
      case "sqrt" => seq => seq.map(i => math.sqrt(i.toDouble)).toString
    }
  }

However, this seems messy to be because of all the repeated anonymous class definitions and repeated type signatures.  This makes the actual math operations less obvious than the first version.

Is there a better way?

Edit:  here is a simple test suite that shows execution of both versions
import org.scalatest.FunSuite

import org.scalatest.FunSuite

class Tests extends FunSuite {

  test("v1"){
    val act = Main.getAction_v1[Double]("sqrt")
    assert(act(Seq(4.0)) === "List(2.0)")
  }

  test("v2") {
    val act = Main.getAction("sqrt")
    assert(act[Double](Seq(4.0)) === "List(2.0)")
  }
}


texts:
I have an ASP.NET CORE API app and now I have an endpoint like:

[HttpPost("receipt")]
[ValidateModel]
[SwaggerResponse(200, typeof(string))]
[SwaggerResponse(400, typeof(string))]
public async Task<IActionResult> SendReceipt([FromBody] EmailDetails emailDetails)
{
    try
    {
        var requestId = HttpContext.TraceIdentifier;
        var connectionId = HttpContext.Features.Get<IHttpConnectionFeature>().ConnectionId;
        await _emailSender.SendEmailAsync(emailDetails, requestId, connectionId);
        return Ok($"The mail has been sent successfully.");
    }
    catch (Exception ex)
    {
        _logger.LogError(ex.Message);
        return BadRequest($"Error sending email: {ex.Message}");
    }
}

While Model looks like:

public class EmailDetails
{
    [Required]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    public string Email { get; set; }

    [Required]
    public string Subject { get; set; }

    [Required]
    public string Receipt { get; set; }
}

So for now as you can see I'm getting an image in Base64 encoded string and then I convert it to the image.

Is it a good idea to get an image in that way? Maybe should I use some alternative solution?

If you need any assistance, please let me know.


texts:
I am trying to create a custom hash from a table. User has many transactions. A transaction has a member_id, company_id, contributions. I am trying to create a custom hash which contains transactions(contributions) happened through a member_id to a company.

    {
    member_id: {
        company: {
            id: "",
            name: ""
        },
        transactions: [
            {
                particulars: "",
                contribution: {
                    contribution1: "",
                    contribution2: ""
                }
            }
        ]
       }
   }

I can simply use

transactions.group(:member_id, :company_id).count

to get the count, but unable to list the transactions grouped to them(Are there any ways?). So i am grouping transaction using group_by(&:member_id) and looping through the hash to generate a hash to my requirement.

Can any one review the bellow code and suggest better way to do this?

user = User.find_by(id: 123)
return {} unless user

transactions = user.transactions
return {} unless transactions.present?

data = {}
transactions.group_by(&:member_id).each do |key, value|
  transactions = []
  company = {}
  value.each do |record|
    company['id'] = record.company_id
    company['name'] = record.company_name
    particulars = record.particulars
    contribution = {}
    contribution['contribution1'] = record.contribution1
    contribution['contribution2'] = record.contribution2
    details = { "particulars": particulars, "contribution": contribution }
    transactions << details
  end
  data[key] = { "company": company, "transactions": transactions }
end


texts:
I'm quite a newbie in Python and I want to speed up this method since it takes very long time especially when the size of the input file in Mbs. Also, I couldn't figure out how to use Cython in the for loop. I'm using this function with other functions to compare files byte by byte. Any recommendations?

# this function returns a file bytes in a list
filename1 = 'doc1.pdf'
def byte_target(filename1):
    f = open(filename1, "rb")
    try:
        b = f.read(1)
        tlist = []
        while True:
            # get file bytes
            t = ' '.join(format(ord(x), 'b') for x in b)
            b = f.read(1)
            if not b:
                break
            #add this byte to the list
            tlist.append(t)

            #print b

    finally:
        f.close()
    return tlist


texts:
Would you have any suggestions for improvements for the code below?

def my_transpose(arr)
  # number of rows
  m = arr.count

  #number of columns
  n = arr[0].count

  transposed_arr = Array.new(n) { Array.new(m) }

  # loop through the rows
  arr.each_with_index do |row, index1|

    # loop through the colons of one row
    row.each_with_index do |num, index2|

      # swap indexes to transpose the initial array
      transposed_arr[index2][index1] = num
      p transposed_arr
    end
  end
  transposed_arr
end


texts:
I'm currently in the process of coding a QuadTree.  The QuadTree seperates into four quadrants, with 1 being the top right and 4 being the bottom right.  I have this code to determine which quadrant the AABB fits into:

int getIndex(AABB aabb) {
    int index = -1;
    double vertMid = bounds.getX() + (bounds.getWidth() / 2);
    double horzMid = bounds.getY() + (bounds.getHeight() / 2);

    // Fits in top
    bool topQuadrant = aabb.getY() < horzMid && aabb.getY() + aabb.getHeight() < horzMid;
    // Fits in botom
    bool bottomQuadrant = aabb.getY() > horzMid && aabb.getY() + aabb.getHeight() < bounds.getY() + bounds.getHeight();

    // Fits in left
    if (aabb.getX() < vertMid && aabb.getX() + aabb.getWidth() < vertMid) {
        if (topQuadrant) {
            index = 1;
        } else if (bottomQuadrant) {
            index = 2;
        }
    }
    // Fits in right
    else if (aabb.getX() > vertMid && aabb.getX() + aabb.getWidth() < bounds.getX() + bounds.getWidth()) {
        if (topQuadrant) {
            index = 0;
        } else if (bottomQuadrant) {
            index = 3;
        }
    }

    return index;
}

-1 indicates it cannot be subdivided
1 indicates top right
2 indicates top left
3 indicates bottom left
4 indicates bottom right

How can I speed it up/make it cleaner? At the moment it is quite slow and I feel like there is an easier way to do it.


texts:
I just watched Raymond Hettinger's talk on making Python more Pythonic and realized I should be putting a lot of his ideas into practice, particularly wrapping API's in a class that makes everything simpler and easy to use. Here's what I'm doing to wrap PyMongo:

from pymongo import MongoClient

class MongoDB(object):
    """Provides a RAII wrapper for PyMongo db connections.
    Available collection functions limited to those in
    attributes_to_pass. Number of simultaneous connection
    users also tracked. """

    attributes_to_pass = ["update", "insert", "count"]
    client = None
    num_users = 0

    def __init__(self, db, collection):
        MongoDB.client = MongoDB.client or MongoClient()
        self.collection = MongoDB.client[db][collection]
        MongoDB.num_users += 1

    def __enter__(self, *args):
        return self

    def __exit__(self, type, value, traceback):
        MongoDB.num_users -= 1
        if MongoDB.num_users is 0:
            self.client.close()

    def __getattr__(self, attr):
        if attr in MongoDB.attributes_to_pass:
            return getattr(self.collection, attr)
        else:
            return getattr(self, attr)

def main():
    with MongoDB(db = "db1", collection = "c1") as m:
        print(m.count())
        m.update({"jello":5} , {"hello":"you"}, upsert = True)
        print(m.count())
        m.insert({"joe":6})
        with MongoDB(db ='db1', collection = 'c2') as j:
            j.insert({"joe":6})
            print(j.count())

if __name__ == "__main__":
    main()

I would really appreciate all suggestions on how to make this better.


texts: class IText - Validates text from Ajax POST | Add consistent return type, defensive coding, functional focus

texts:
I denotes independent, no dependencies.

<?php
/**
 *Input - One Dimensional Non-Empty Post Array
 *Ouput - Boolean on pass or fail
 */
class IText
{
    private $text_array = array();
    private $patterns = array(
       'domain' =>              '/:\/\/(www\.)?(.[^\/:]+)/',
       'prefix_url' =>          '/^(http:)|(https:)\/\//',
       'url' =>                 '/^.{1,2048}$/',
       'tweet' =>               '/^.{1,40}$/',
       'title' =>               '/^.{1,32}$/',
       'name' =>                '/^.{1,64}$/',
       'email' =>               '/^.{1,64}@.{1,255}$/',
       'pass' =>                '/^.{6,20}$/'
    );
    public function __construct()
    {
        if ( count( $_POST ) === 0 )
        {
            echo "Hack Attempt";
            return;
        }
        else
        {
            foreach( $_POST as $key => $value )
            {
                if( !is_scalar( $value ) )
                {
                    echo "Hack Attempt";
                    return;
                }
                $this->text_array[ $key ] = htmlentities( $value );
            }
        }
    }
    public function get( $key ) // basic getter
    {
        return $this->text_array[ $key ];
    }
    public function set( $key, $value ) // basic setter
    {
        $this->text_array[ $key ] = $value;
    }
    public function checkPattern( $pattern ) // checks for pattern and returns bool
    {
        return ( ( boolean )preg_match( $this->patterns[ $pattern ], $this->text_array[ $pattern ] ) );
    }
    public function checkEmpty() // checks for empty and returns bool
    {
        return ( !in_array( '', $this->text_array, TRUE ) );
    }
}


texts: Multiple if-statements with overwriting lists

texts:
I currently have the following piece of code in place that attempts to find matches within a list, based on a priority system:
possible_combinations = ["ABC", "AB", "A", "D"]

if len(possible_combinations) >= 1:
    chosen_combination = [comb for comb in possible_combinations if ("A" in comb) and ("C" in comb)]
    if (len(chosen_combination) == 0):
        chosen_combination = [comb for comb in possible_combinations if ("A" in comb)]
        if (len(chosen_combination) == 0):
            chosen_combination = [comb for comb in possible_combinations if ("C" in comb)]
            if (len(chosen_combination) == 0):
                raise ValueError(f"No match found.")

print(chosen_combination)

['ABC']

Is there any way I could refactor this code to get rid of these if-statements, and thereby make my code look nicer?


texts: Automatically remove O365 license from AD user when using powershell

texts:
As you can see I have been using multiple conditions such as if, elseif, else, but it takes too much time to complete the process.

How can I improve the speed of the script?

Import-Module ActiveDirectory
Import-Module MSOnline

$password = ConvertTo-SecureString 'PASSWORD' -AsPlainText -Force
$LiveCred = New-Object System.Management.Automation.PSCredential ("username@domain.com", $password)
New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection

Connect-MsolService -Credential $Livecred

$userID = Import-Csv "c:\export\list.csv"
$LogFile = "C:\export\logs.txt"
foreach ($user in $userID)
{

    $ADuser = Get-ADUser -Filter "EmployeeId -eq $($user.EmployeeID)" -Properties whenCreated, Enabled, SAMAccountName
    $O365User = Get-MsolUser -UserPrincipalName $ADuser.UserPrincipalName

    if (($ADuser.Enabled -eq $true) -and ($O365User.isLicensed -eq $true))
    {
        Get-MsolUSer -UserPrincipalName $ADuser.UserPrincipalName
        Set-MsolUserLicense -UserPrincipalName $ADuser.UserPrincipalName -RemoveLicenses "company:ENTERPRISEPACK"
        #move user OU, change description, disable account, remove SG members list
        #$Date = Get-Date -Format MM-dd-yyyy
        #Set-ADUser -Identity $ADuser.SAMAccountName -Replace @{info="User disabled at $Date"}
        # $User has been disabled and remove office 365 licence from user.
        #"$ADuser.SAMAccountName has been disabled and remove office 365 licence from user." | Out-File $LogFile -Append -Force

    }
    elseif (($ADuser.Enabled -eq $true) -and ($O365User.isLicensed -eq $false))
    {
        #move user OU, change description, disable account, remove SG members list
        #Set-ADUser username -Replace @{info='New info for the notes field'}
        #"$ADuser.SAMAccountName has been disabled and already without office 365 licence." | Out-File $LogFile -Append -Force

    }
    elseif (($ADuser.Enabled -eq $false) -and ($O365User.isLicensed -eq $false))
    {
        #do nothing
        #"$ADuser.SAMAccountName has been already disabled and already without office 365 licence." | Out-File $LogFile -Append -Force

    }
    elseif (($ADuser.Enabled -eq $false) -and ($O365User.isLicensed -eq $true))
    {
        Get-MsolUSer -UserPrincipalName $ADuser.UserPrincipalName
        Set-MsolUserLicense -UserPrincipalName $ADuser.UserPrincipalName -RemoveLicenses "company:ENTERPRISEPACK"
        #"$ADuser.SAMAccountName has been already disabled and but revoke office 365 licence." | Out-File $LogFile -Append -Force

    }
    else
    {
        #User does not exist in AD
        #"$user.EmployeeID does not exist in Active Directory." | Out-File $LogFile -Append -Force

    }

}


texts:
I imagine I get a minuscule performance improvement by doing the %3 as a branch off the %5 rather than the other way round or as an if '%15'. Am I correct about that? (I know there is no practical difference)

#include <stdio.h>

///Write a program that prints the numbers from 1 to 100.
///But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz".
///For numbers which are multiples of both three and five print "FizzBuzz".
int main()
{
    int a=1;
    while (a<101)
    {
        if (a%5==0)
        {
            if (a%3==0)
            {
                printf("FizzBuzz\n");
            }
            else
            {
                printf("Buzz\n");
            }
        }
        else if(a%3==0)
        {
            printf("Fizz\n");
        }
        else
        {
            printf("%d\n",a);
        }
        a++;
    }
return 0;
}


texts:
Kata: https://www.codewars.com/kata/range-extraction/python

  A format for expressing an ordered list of integers is to use a comma separated list of either

  individual integers
  or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example ("12, 13, 15-17")

  Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format.

  Example:

solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20])
 # returns "-6,-3-1,3-5,7-11,14,15,17-20"

  Courtesy of rosettacode.org

My Code

def solution(lst):
    res = []
    if lst:
        tmp, i, ln = lst[0], 0, len(lst)
        while i < ln:
            tmp, j = lst[i], i
            while j < ln - 1 and lst[j+1] == lst[j]+1:
                j += 1
            if j - i > 1:
                tmp = str(lst[i]) + "-" + str(lst[j])
                i = j+1
            else:
                i = (j if j > i else i+1)
            res.append(tmp)
    return ",".join(str(x) for x in res)


texts: Zip-like construction of objects from parameter collections

texts:
This little function can make object creation much easier.
Sometimes you need to switch between representing your data as objects vs. having the members in separate containers.

Example:

class Foo {
public:
    Foo(int a_, double b_): a(a_), b(b_){}

    int a;
    double b;
};

And then:

std::vector<int> as = {1,2,3,4,5};
std::vector<double> bs = {6.0,7.0,8.0,9.0,10.0};
std::vector<Foo> foos = zipConstruct<Foo>(as, bs);

cout << foos[3].a << ", " << foos[3].b << endl; // 4, 9

Using:

template <typename T, typename... Arg>
std::vector<T> zipConstruct(std::vector<Arg> const&... argVec)
{
    std::vector<size_t> sizes = {argVec.size()...};
    assert(std::all_of(sizes.begin(), sizes.end(), [&](size_t s){return s=sizes[0];}));
    size_t size = sizes[0];

    std::vector<T> result;
    result.reserve(size);

    for (size_t i = 0; i < size; ++i)
    {
        result.emplace_back((argVec[i])...);
    }

    return result;
}

Does this make sense?


texts: spec_helper.rb for RSpec, Capybara, FactoryGirl, Spork and Devise

texts:
Having been through hundreds of often-conflicting posts on testing with RSpec, Capybara, FactoryGirl, Spork, Guard and Devise without Cucumber, this is the spec_helper which "seems to" work.

I'm bracing for it to blow up or not work like the previous attempts.

Here's my spec_helper.rb

Questions:

Is there something in it likely to cause trouble?
Are there inefficiencies? Anything which ought to be done better?

require 'rubygems'
require 'spork'

def start_simplecov
  require 'simplecov'
  SimpleCov.start 'rails' unless ENV["SKIP_COV"]
end

def spork?
  defined?(Spork) && Spork.using_spork?
end

def simplecov?
  defined?(SimpleCov) && SimpleCov.using_simplecov?
end

def setup_environment

  # This file is copied to spec/ when you run 'rails generate rspec:install'
  ENV["RAILS_ENV"] ||= 'test'

  start_simplecov unless (spork? || !simplecov?)

  if spork?
    ENV['DRB'] = 'true'
#    require "rails/mongoid"
#    Spork.trap_class_method(Rails::Mongoid, :load_models)
    require "rails/application"
    Spork.trap_method(Rails::Application::RoutesReloader, :reload!)
  end

  require File.expand_path("../../config/environment", __FILE__)
  require 'rspec/rails'
#  require 'rspec/autorun'

  require 'capybara/rails'
  require 'capybara/rspec'
  Capybara.default_host = 'http://localhost'
  Capybara.server_port = 3000
  include Capybara::DSL

  require 'factory_girl_rails'
 # FactoryGirl.factories.clear
#  FactoryGirl.find_definitions

  Rails.backtrace_cleaner.remove_silencers!

  require 'database_cleaner'

#  DatabaseCleaner.orm = "mongoid"
  DatabaseCleaner.strategy = :truncation

  Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}

  RSpec.configure do |config|

    config.mock_with :rspec

    # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
    # config.fixture_path = "#{::Rails.root}/spec/fixtures"

    # If you're not using ActiveRecord, or you'd prefer not to run each of your
    # examples within a transaction, remove the following line or assign false
    # instead of true.
    config.use_transactional_fixtures = true

    config.before(:suite) do
      DatabaseCleaner.clean_with(:truncation)
    end

    config.before(:each) do
      DatabaseCleaner.clean
    end

#    config.include Mongoid::Matchers
    config.include Devise::TestHelpers, :type => :controller
    config.extend ControllerMacros, :type => :controller
    config.include FactoryGirl::Syntax::Methods
    Capybara.javascript_driver = :rack_test

    # If true, the base class of anonymous controllers will be inferred
    # automatically. This will be the default behavior in future versions of
    # rspec-rails.
    config.infer_base_class_for_anonymous_controllers = false
  end
end

def each_run
  if spork?
#    FactoryGirl.definition_file_paths = [File.join(Rails.root, 'spec', 'factories')]
#    FactoryGirl.find_definitions
#    FactoryGirl.reload

    Pollsrv::Application.reload_routes!
    FactoryGirl.factories.clear
    Dir.glob("#{::Rails.root}/spec/factories/*.rb").each { |file| load "#{file}" }
  end

  # Requires supporting ruby files with custom matchers and macros, etc,
  # in spec/support/ and its subdirectories.
end

# If spork is available in the Gemfile it'll be used but we don't force it.
unless (begin; require 'spork'; rescue LoadError; nil end).nil?
  Spork.prefork do
    # Loading more in this block will cause your tests to run faster. However,
    # if you change any configuration or code from libraries loaded here, you'll
    # need to restart spork for it take effect.
    setup_environment
    ActiveSupport::Dependencies.clear
#    Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}
  end

  Spork.each_run do
    # This code will be run each time you run your specs.
    each_run
  end
else
#  Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}
  setup_environment
  each_run
end


texts: Finding MinMax values and returning a tuple as a result

texts:
I was coding some tooling stuff when I started to ponder whether the best return type for a Range / MinMax method applied on a IEnumerable method.

I am using the value the C# 7 Tuples like below, but tempted to create my own class with readonly fields.

    public static (TSource Min, TSource Max) MinMax<TSource>(this IEnumerable<TSource> source, IComparer<TSource> comparer)
    {
        using (var sourceIterator = source.GetEnumerator())
        {
            if (!sourceIterator.MoveNext())
            {
                throw new InvalidOperationException("Sequence contains no elements");
            }

            var max = sourceIterator.Current;
            var min = sourceIterator.Current;

            while (sourceIterator.MoveNext())
            {
                var candidate = sourceIterator.Current;

                if (comparer.LeftStrictlyLesserThanRight(candidate, min))
                {
                    min = candidate;
                }

                if (comparer.LeftStrictlyGreaterThanRight(candidate, max))
                {
                    max = candidate;
                }
            }

            return (min, max);
        }
    }

Utilities are defined as below:

internal static class ComparerExtensions
{
    public static bool LeftStrictlyGreaterThanRight<T>(this IComparer<T> comparer, T left, T right)
    {
        return comparer.Compare(left, right) > 0;
    }
    public static bool LeftStrictlyLesserThanRight<T>(this IComparer<T> comparer, T left, T right)
    {
        return comparer.Compare(left, right) < 0;
    }
}

What do you think is the best, knowing that creating a reference type would bring some additional allocations and GC work (I mean that was the whole point to have struct-like tuples in C# 7). What bothers me with the tuple is that fields are not readonly and we cannot prevent users of the method to mess up and break flow.

I don't know maybe it's just me and my over-defensive coding style and bad experience using Python where coders are considered as "adults"?


texts:
I have a websocket connection with 3-rd party API. The API returns a lot of data, in a peak hours it returns hundreds messages per second. I need to process the data for two purposes: save everything in a DB and send some data to RabbitMq.

The idea is the following:
I want to save data to DB when batch size is 1000 or by timeout which is equal to 3 seconds.

I want to publish data to RabbitMQ by 1 second timeout. It's a kind of throttling, because there are a lot of data. Moreover, I need to select the last record for the specific ticker, I have done it in the ActionBlock, f.e: we have the following records in the batch:

  {"Ticker": "MSFT", "DateTime": '2019-05-14T10:00:00:100'}
  {"Ticker": "MSFT", "DateTime": '2019-05-14T10:00:00:150'}
  {"Ticker": "AAPL", "DateTime": '2019-05-14T10:00:00:300'}

I need to publish the last for the specific ticker only, so after filtering there will be 2 records that I am going to publish:

  {"Ticker": "MSFT", "DateTime": '2019-05-14T10:00:00:150'}
  {"Ticker": "AAPL", "DateTime": '2019-05-14T10:00:00:300'}

Full code:

public class StreamMessagePipeline < T > where T: StreamingMessage {
    private readonly BatchBlock < T > _saveBatchBlock;
    private readonly BatchBlock < T > _publishBatchBlock;

    public StreamMessagePipeline() {
        _saveBatchBlock = new BatchBlock < T > (1000);
        _publishBatchBlock = new BatchBlock < T > (500);

        SetupSaveBatchPipeline();
        SetupPublishBatchPipeline();
    }

    private void SetupSaveBatchPipeline() {
        var saveBatchTimeOut = TimeSpan.FromSeconds(3);
        var saveBatchTimer = new Timer(saveBatchTimeOut.TotalMilliseconds);

        saveBatchTimer.Elapsed += (s, e) = >_saveBatchBlock.TriggerBatch();

        var actionBlockSave = new ActionBlock < IEnumerable < T >> (x = >{
            //Reset the timeout since we got a batch
            saveBatchTimer.Stop();
            saveBatchTimer.Start();

            Console.WriteLine($ "Save to DB : {x.Count()}");
        });

        _saveBatchBlock.LinkTo(actionBlockSave, new DataflowLinkOptions {
            PropagateCompletion = true
        });
    }

    private void SetupPublishBatchPipeline() {
        var publishBatchTimeOut = TimeSpan.FromSeconds(1);
        var publishBatchTimer = new Timer(publishBatchTimeOut.TotalMilliseconds);

        publishBatchTimer.Elapsed += (s, e) = >_publishBatchBlock.TriggerBatch();

        var actionBlockPublic = new ActionBlock < IEnumerable < T >> (x = >{
            var res = x.GroupBy(d => d.Ticker).Select(d = >d.OrderByDescending(s =>s.DateTime).FirstOrDefault()).ToList();

            Console.WriteLine($ "Publish data to somewhere : {res.Count()}");
            //Reset the timeout since we got a batch
            publishBatchTimer.Stop();
            publishBatchTimer.Start();

        });

        _publishBatchBlock.LinkTo(actionBlockPublic, new DataflowLinkOptions {
            PropagateCompletion = true
        });
    }

    public async Task Handle(T record) {
        await _saveBatchBlock.SendAsync(record);
        await _publishBatchBlock.SendAsync(record);
    }

}


texts: Merge two sorted linked lists without recursion

texts:
Is this an effective way for merging two lists? It seemed too long.

struct Node {
    int item;
    Node *next;
};

Method:

Node* mergeTwo(Node* headA, Node* headB)
{
Node* currentA = headA;
Node* currentB = headB;

Node* headC = NULL;
Node* currentC = NULL;

while (currentA != NULL && currentB != NULL)
{
    if (currentA->item < currentB->item)
    {
        Node* node = new Node();
        node->item = currentA->item;
        node->next = NULL;

        if (headC == NULL)
            headC = node;
        else
            currentC->next = node;

        // update currents
        currentC = node;
        currentA = currentA->next;
    }
    else // currentB->item < currentA->item
    {
        Node* node = new Node();
        node->item = currentB->item;
        node->next = NULL;

        if (headC == NULL)
            headC = node;
        else
            currentC->next = node;

        // update currents
        currentC = node;
        currentB = currentB->next;
    }
}

// one of currentA or currentB will not be NULL
while (currentA != NULL)
{
    Node* node = new Node();
    node->item = currentA->item;
    node->next = NULL;

    // in case like: A={13,15}, B={4,6}
    if (headC == NULL)
        headC = node;
    else
        currentC->next = node;

    // update currents
    currentC = node;
    currentA = currentA->next;
}

while (currentB != NULL)
{
    Node* node = new Node();
    node->item = currentB->item;
    node->next = NULL;

    // in case like: A={3,5}, B={7,8}
    if (headC == NULL)
        headC = node;
    else
        currentC->next = node;

    // update currents
    currentC = node;
    currentB = currentB->next;
}
return headC;
}


texts: Partitions of a number (backtracking) - time efficiency

texts:
I had to write an algorithm that prints the partitions of a natural number in lexicographic order. Example of I/O:

  If the algorithm reads from partitiinumar.in.txt n=5

  In partitiinumar.out.txt we should have:

  1 1 1 1 1

  1 1 1 2

  1 1 3

  1 2 2

  1 4

  2 3

  5

The problem is that I have a time limit for the execution of the algorithm of 0.5 sec and for values of n higher than 9 (1<=n<=40), the exection time increases a lot, so I have to optimize the code. I ask for some time efficiency suggestions. Here is the code:

#include <fstream>

using namespace std;

ofstream out("partitiinumar.out.txt");

int n, solutions[41];

int solution(int k)
{
    int S = 0;
    for (int i = 1; i < k; i++)
        S = S + solutions[i];

    if (S == n)
        return 1;
    else
        return 0;
}

int succesor(int k)
{
    if (solutions[k] < n)
    {
        solutions[k]++;
        return 1;
    }
    else
        return 0;
}

int valid(int k)    // I guess that this function is the reason for the lack of efficiency. I created this function to select only the solutions that have the numbers in a increasing order
{
    if (k > 1)
        if (solutions[k] >= solutions[k - 1])
            return 1;
        else
            return 0;

    else return 1;
}

void backtracking(int k)
{
    if (solution(k))
    {
        for (int i = 1; i < k; i++)
            out << solutions[i] << " ";
        out << '\n';
    }
    else if (solution(k)==0 && k<=n)
    {
        solutions[k] = 0;
        while (succesor(k))
            if (valid(k))
                backtracking(k + 1);
    }

}

int main()
{
    ifstream in("partitiinumar.in.txt"); in >> n; in.close();

    if (n >= 1 && n <= 40)
        backtracking(1);

    out.close();

    return 0;
}


texts: Find offset that minimizes squared difference between two vectors of different size

texts:
I am working on a project where the hotspot is some code that is supposed to find an offset, such that the squared differences between a reference vector and a given vector becomes minimal. The core function is this:

#include <vector>
#include <map>
typedef std::vector<double> vect_d

double sqDiffSum(const vect_d& ref, const vect_d& x,int offset){
    size_t scale = ref.size() / x.size(); // ref.size() is always n*x.size()
    double sum = 0;
    int counter = 0;
    for (size_t i=0;i<x.size();i++){
        for (size_t j=0;j<scale;j++){
            int bin = i*scale + j - offset;
            if (bin >= 0 && bin < (int)ref.size()){
                double diff = ref[bin] - x[i];
                sum += diff * diff;
                counter++;
            }
        }
    }
    return sum / counter;
}

This is called from some minimization routine, that (for now) I dont want to change. It varies the offset to get the minimum sqDiffSum. I know that I could probably do the task faster by using a FFT, but for now I want to see how much I can get out of the current approach. I could already make it faster (roughly x2.5) by adding some memoization:

double callSqDiffSum(const vect_d& ref, const vect_d& x,int offset,bool firstCall){
    static std::map<int,double> memo;
    if (firstCall){ memo.clear(); }
    else {
        std::map<int,double>::iterator found = memo.find(offset);
        if (found != memo.end()){
            return found->second;
        }
    }
    double result = sqDiffSum(ref,x,offset);
    memo[offset] = result;
    return result;
}

However, it is still too slow. There are several points that in principle I could optimize, but for each I have my doubts whether it will bring any benefit:

The reference vector ref is actually always the same, thus I could avoid passing it around at all.
The size of the vectors is always the same, so actually there is no need for std::vector, but if possible I would like to avoid c-style arrays and I dont expect too much improvement by not using vectors here.
The innermost loop has some branching, that could be avoided

Is there anything that comes to your mind to make this more efficient? Is my assumption that the above points are not really worth to change wrong?

Please note that this is pre-C++11.


texts:
I have implemented binary search in JavaScript.

I run it on node.

I pass an comma separated string of numbers in ascending order as first argument and the number to be searched in the second argument.

the code is as follows,

var myArray = [],
searchNum = undefined;

// below function is used to capture the
// commandline parameters for array and the
// number to be searched
(function(){
    process.argv.forEach(function (val, index, array) {
        var idx = 0, ar = undefined;

        try{

            if(index === 2){

                ar = val.split(",");

                // convert the numbers present as string values is array
                // to array of numbers
                for(idx = 0; idx < ar.length; idx++){
                    myArray.push(parseInt(ar[idx]));
                }
            }// end of if

            // third index is the number to be searched.
            if(index === 3){
                searchNum = parseInt(val)
            }

        }catch(e){
            console.log(e)
        }

    });
})();

console.log(" SEARCH NUMBER ",searchNum," in array ",myArray);
console.log(" Number ",searchNum," "+binarySearch(myArray,searchNum));

// binary-Search implementation
function binarySearch(myArray,numberToSearch){
    var arrayLength = myArray.length,
        midIndex = parseInt(arrayLength/2),
        subArray = undefined,
        lowerIndex = 0,
        higherIndex = 0;

    if(myArray[midIndex] === numberToSearch){
        return "is Found";

    // search the number in left side if array
    // i.e. number is found to the left of the
    // middle Index
    }else if(midIndex !== 0 && myArray[midIndex] > numberToSearch){
        lowerIndex = 0;
        higherIndex = midIndex;
        subArray = myArray.slice(lowerIndex,higherIndex); // create the sub-array
        return binarySearch(subArray,numberToSearch); // search the number in the subarray

    // search the number in right side if array
    // i.e. number is found to the right of the
    // middle Index
    }else if(midIndex !== 0 && myArray[midIndex] < numberToSearch){ // search the number in right side if array
        lowerIndex = midIndex + 1;
        higherIndex = arrayLength;
        subArray = myArray.slice(lowerIndex,higherIndex); // create the sub-array
        return binarySearch(subArray,numberToSearch); // search the number in the subarray
    }else{
        return "can't be found";
    }
}// end of binarySearch method

I run the above as follows

E:\RahulShivsharan\MyPractise\DesignPatternsInJavaScript>node binarySearch.js 34,45,67,89,90,123,345 300
 SEARCH NUMBER  300  in array  [ 34, 45, 67, 89, 90, 123, 345 ]
 Number  300  can't be found

E:\RahulShivsharan\MyPractise\DesignPatternsInJavaScript>node binarySearch.js 34,45,67,89,90,123,345 45
 SEARCH NUMBER  45  in array  [ 34, 45, 67, 89, 90, 123, 345 ]
 Number  45  is Found

E:\RahulShivsharan\MyPractise\DesignPatternsInJavaScript>

Requesting to please review my above implementation, and give your valuable feedback.


texts: Algorithm for competing cells of 0s and 1s

texts:
I'm working on a practice algorithm problem, stated as follows:

  There are eight houses represented as cells. Each day, the houses compete with adjacent ones. 1 represents an "active" house and 0 represents an "inactive" house. If the neighbors on both sides of a given house are either both active or both inactive, then that house becomes inactive on the next day. Otherwise it becomes active. For example, if we had a group of neighbors [0, 1, 0] then the house at [1] would become 0 since both the house to its left and right are both inactive. The cells at both ends only have one adjacent cell so assume that the unoccupied space on the other side is an inactive cell.

  Even after updating the cell, you have to consider its prior state when updating the others so that the state information of each cell is updated simultaneously.

  The function takes the array of states and a number of days and should output the state of the houses after the given number of days.

  Examples:

  input: states = [1, 0, 0, 0, 0, 1, 0, 0], days = 1
  output should be [0, 1, 0, 0, 1, 0, 1, 0]
  input: states = [1, 1, 1, 0, 1, 1, 1, 1], days = 2
  output should be [0, 0, 0, 0, 0, 1, 1, 0]

Here's my solution:

def cell_compete(states, days):
    def new_state(in_states):
        new_state = []
        for i in range(len(in_states)):
            if i == 0:
                group = [0, in_states[0], in_states[1]]
            elif i == len(in_states) - 1:
                group = [in_states[i - 1], in_states[i], 0]
            else:
                group = [in_states[i - 1], in_states[i], in_states[i + 1]]
            new_state.append(0 if group[0] == group[2] else 1)
        return new_state

    state = None
    j = 0
    while j < days:
        if not state:
            state = new_state(states)
        else:
            state = new_state(state)
        j += 1
    return state

I originally thought to take advantage of the fact they are 0s and 1s only and to use bitwise operators, but couldn't quite get that to work.

How can I improve the efficiency of this algorithm or the readability of the code itself?


texts:
I wrote a short bash script for a completion check of downloading images. If you have any good ideas, please tell me them. Thank you.
#!/bin/sh

# if a directory name is assigned

if [ $# -eq 1 ]; then

  a=`ls -1 $1/*.jpg | wc -l`
  b=`grep jpg $1/tmp.sh | wc -l`
  if [ $a = $b ]; then
    echo $1
  fi
  exit
fi

# if some directory names are assigned

if [ $# -gt 1 ]; then
  for dir1 in "$@"; do
    ./done.sh $dir1
  done
fi

# if directory names are not assigned

if [ $# -eq 0 ]; then
  ls -d */ | xargs ./done.sh
fi


texts: Find, on a sequence of size L, the number that appears more than L/2 times

texts:
Yes, yet another challenge on CodeEval!

This one has the purpose of finding the major element of a sequence: the element which appears in a sequence of size L more than L/2 times. I have this:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class Main {
    public static void main (String[] args) throws IOException {
        File file = new File(args[0]);
        BufferedReader buffer = new BufferedReader(new FileReader(file));
        String line;
        String[] numbersRaw;
        int[] numbers;
        while ((line = buffer.readLine()) != null) {
            line = line.trim();
            numbersRaw = line.split(",");
            numbers = new int[numbersRaw.length];
            for(int i = 0; i < numbersRaw.length; i++){
                numbers[i] = Integer.valueOf(numbersRaw[i]);
            }
            System.out.println(mostFrequentElement(numbers));
        }
    }

    private static String mostFrequentElement(int[] arr) {
        Arrays.sort(arr);
        int counter = 0, big = -1, bigCounter = -1;
        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[i] == arr[i + 1]) {
                counter++;
            }
            else {
                counter++;
                if (counter > bigCounter) {
                    big = arr[i];
                    bigCounter = counter;
                }
                counter = 0;
            }
        }
        if(bigCounter > arr.length / 2) {
            return big + "";
        }
        return "None";
    }
}

I have this solution, with appears to solve the challenge - however I think its performance is a bit sluggish (measured running time is about 1300 milliseconds). Is there any way to improve this?


texts:
I'm trying to understand how to use pydantic for data parsing & validation.
The idea I had in mind was following:

I have a list of DOI names for which I need to collect metadata
I could use pydantic to test if the DOI name is valid

if it's valid, I proceed with making a request to scite api
if not, the code raises an exception instead of calling api

Very basic idea as you see.

The code:
scite_utils.py
import requests
from ratelimit import limits, sleep_and_retry
from pydantic import BaseModel, ValidationError, constr

class DOI(BaseModel):
    name: constr(regex=r"^10\.\d{4,9}/[-._;()/:a-zA-Z0-9]+$")

@sleep_and_retry
@limits(calls=40, period=60) # api ratelimits
def remote_call(endpoint: str):
    r = requests.get(f"https://api.scite.ai/{endpoint}")
    r.encoding = "UTF-8"
    return r.json()

def get_paper(doi: DOI):
    if not isinstance(doi, DOI):
        try:
            doi = DOI(name=doi).name
        except ValidationError:
            return
    return remote_call(endpoint=f"papers/{doi}")

test.py
import pandas as pd
from typing import List
from scite_utils import DOI, get_paper

# a sample of 5 but realisticlly - thousands?
DOIs = [
    "10.12724/ajss.47.0",
    "10.31124/advance.12630065.v1",
    "obv_error",
    "10.1122ajss.123.9",
    "10.1080/09662830500528294"
]

def create_table(names: List[DOI]):
    data = [get_paper(name) for name in names]
    return pd.DataFrame(
        publication
        for publication in data
        if publication is not None
    )

if __name__=="__main__":
    result = create_table(DOIs)
    print(result)

Questions:

Is this a valid use case for pydantic?
Should I validate DOI name inside of the function that makes a request
(or is there a better place for it, like a separate function)?
Doesn't it look awkward generally? I feel like I'm missing the point,
because I could've written a custom function with re to validate DOI name.


texts:
from itertools import izip_longest

def partition(n, iterable):
   p = izip_longest(*([iter(iterable)] * n))
   r = []
   for x in p:
       s = set(x)
       s.discard(None)
       r.append(list(s))
   return r

print partition(2, range(100))

I saw it from a recruit and the company said there were potential problems, but I can't find out anything wrong with my test case:

print partition(2, range(100))
print partition(1, range(100))
print partition(-1, range(100))
print partition(101, range(100))


texts: Find the oldest person by Lithuanian National Identification Number

texts:
I made a program which parses the NIDs from kodai.txt file and calculates the oldest woman and man and outputs their DOB.

#include <iostream>
#include <fstream>
#include "math.h"
using namespace std;

enum Genders {
    Man, Woman
};

struct Person {
    Genders gender;
    int dobYear;
    int dobMonth;
    int dobDay;
    long code;
};

Person parsePerson(long kodas) {
    Person person;

    kodas = kodas / 10000;
    int firstNumber = kodas / 1000000;

    switch(firstNumber) {
        case 1:
            person.gender = Genders::Man;
            person.dobYear = 1800;
            break;
        case 2:
            person.gender = Genders::Woman;
            person.dobYear = 1800;
            break;
        case 3:
            person.gender = Genders::Man;
            person.dobYear = 1900;
            break;
        case 4:
            person.gender = Genders::Woman;
            person.dobYear = 1900;
            break;
        case 5:
            person.gender = Genders::Man;
            person.dobYear = 2000;
            break;
        case 6:
            person.gender = Genders::Woman;
            person.dobYear = 2000;
            break;
    }

    kodas = kodas % 1000000;
    int years = kodas / 10000;

    person.dobYear += years;

    kodas = kodas % 10000;

    person.dobMonth = kodas / 100;

    kodas = kodas % 100;

    person.dobDay = kodas;

    cout << person.dobDay << endl;
    return person;
}

bool comparePerson (Person p1, Person p2) {
    if (p1.dobYear < p2.dobYear) {
        return true;
    }

    if (p1.dobYear == p2.dobYear) {
        if (p1.dobMonth < p2.dobMonth) {
            return true;
        }

        if (p1.dobMonth == p2.dobMonth) {
            if (p1.dobDay < p2.dobDay) {
                return true;
            }
        }
    }

    return false;
}

int main () {
    ifstream kodai("kodai.txt");

    Person oldestMan;
    Person oldestWoman;

    oldestMan.dobYear = 9999;
    oldestMan.dobMonth = 9999;
    oldestMan.dobDay = 9999;

    oldestWoman.dobYear = 9999;
    oldestWoman.dobMonth = 9999;
    oldestWoman.dobDay = 9999;

    long code;

    while (kodai >> code) {
        Person person = parsePerson(code);

        if (person.gender == Genders::Woman) {
            if (comparePerson(person, oldestWoman)) {
                oldestWoman = person;
            }
        } else if (person.gender == Genders::Man) {
            if (comparePerson(person, oldestMan)) {
                oldestMan = person;
            }
        }

    }

    cout << "Oldest man: " << oldestMan.dobYear << "-" << oldestMan.dobMonth << "-" << oldestMan.dobDay << endl;
    cout << "Oldest woman: " << oldestWoman.dobYear << "-" << oldestWoman.dobMonth << "-" << oldestWoman.dobDay << endl;
}

Example kodai.txt:

33309240064
40212220064
50211020064
10001010064
20001010064

Can you give me any suggestions or problems that you might see?


texts: Overwrite disk space for the purpose of deleting old data

texts:
I have written a little program that overwrites memory. It creates useless files in a folder named "folder" (I am so creative). The purpose is to overwrite old data. It's not a very professional program because I am a beginner, but I think it should do for which it is destined: exhaust memory and thus maybe overwrite old data that was stored on it. If you have tips for me how to imrove this program or how to make it faster in it's execution I would be thankful!

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int create_files(int number_of_files, int number_of_values);

int main()
{
    int number_of_files;
    int number_of_values;

    srand(time(NULL));

    printf("before using this program create a folder with the name \"folder\"\nin the same folder this program is located\n");
    printf("number of files: ");
    scanf("%d", &number_of_files);
    printf("number of values: ");
    scanf("%d", &number_of_values);

    create_files(number_of_files, number_of_values);

}

void create_files(int number_of_files, int number_of_values)
{
    for(int i = 0; i < number_of_files; i++)
    {
        FILE * file;
        char file_name[30] = "./folder/";
        char file_number[20];
        sprintf(file_number, "%d", i);
        strcat(file_name, file_number);
        file = fopen(file_name, "w+");

        for(int j = 0; j < number_of_values; j++)
        {
            int random_value = rand();
            fprintf(file, "%d", random_value);
        }
        fclose(file);
    }
}


texts: Python multi-threaded kubernetes watcher

texts:
My program (which eventually will be containerised) should be able to do the following:

continuously listening for deployment and daemonsets in kubernetes (2 threads)
collect info needed (like annotations)
use the info collected in order to create objects in a remote database

I could use some peer review for the thread part, which looks like this currently:

#first thread to watch for deployments
def watch_deployments():
    v1 = client.AppsV1Api()
    w = watch.Watch()
    last_seen_version = v1.list_deployment_for_all_namespaces().metadata.resource_version
    while True:
        for item in w.stream(v1.list_deployment_for_all_namespaces, pretty="pretty", resource_version=last_seen_version):
                _ = {item["object"].metadata.name:[item["object"].kind, item["object"].metadata.namespace, item["object"].metadata.resource_version, item["object"].metadata.annotations]}
                depl_lst.put(_)

def watch_daemonsets():
    v1 = client.AppsV1Api()
    w = watch.Watch()
    last_seen_version = v1.list_daemon_set_for_all_namespaces().metadata.resource_version
    while True:
        for item in w.stream(v1.list_daemon_set_for_all_namespaces, pretty="pretty", resource_version=last_seen_version):
            _ = {item["object"].metadata.name:[item["object"].kind, item["object"].metadata.namespace, item["object"].metadata.resource_version, item["object"].metadata.annotations]}
            depl_lst.put(_)

if __name__ == '__main__':
    current_obj = {}
    depl_lst = Queue()
    thread.start_new_thread(watch_deployments, ())
    thread.start_new_thread(watch_daemonsets, ())

    while True:
        for i in range(depl_lst.qsize()):
            current_obj = depl_lst.get()

            #add object is the function in order to create the item in the remote database, not listed here
            add_object()

            depl_lst.task_done()

Its the same thing with what is being done here but in this case, the asyncio was being used:
https://medium.com/@sebgoa/kubernets-async-watches-b8fa8a7ebfd4


texts:
I'm scraping a title and a link from a website and placing them in a single array.
The $i variable seems a bit wrong to me, or is it perfectly fine?

$linkQuery = $xpath->query("//div[@class='news-archive']//a/@href");
$titleQuery = $xpath->query("//div[@class='news-archive']//a");

$data = [];

foreach ($linkQuery as $link) {
    $data[] = array('link' => $link->value);
}

$i = 0;
foreach ($titleQuery as $title) {
    $data[$i]['title'] = $title->nodeValue;
    $i++;
}

I do like the structure of the Array:

Array (
    [0] => Array
        (
            [link] => http://www.gpupdate.net/nl/f1-nieuws/321783/force-india-vreest-voor-deelname-aan-laatste-test/
            [title] => Force India vreest voor deelname aan laatste test
        )


texts: Python calculate arrangements of sequence

texts:
I have just started thinking about probabilities. A Problem that come up was how to calculate all the potential arrangements for a given sequence. By arrangement I mean unique permutation.

I initially used this method:

from itertools import permutations

sequence = '11223344'
len(set(permutations(sequence)))
# 2520

But for long sequences this can take a long time! (or run out of memory)

I came up with this function arrangements

from math import factorial
from functools import reduce
from operator import mul

def arrangements(sequence):
    return factorial(len(sequence))/reduce(mul,
           [factorial(sequence.count(i)) for i in set(sequence)])

# arrangements(sequence)
# 2520.0

My thinking is this:

For a given length sequence with all unique items there are factorial(len(sequence)) permutations.

For every repeated item in the sequence there will be factorial(#repeats) that will result in the same permutation.

My function calculates all permutations / all repeated permutations.

I'm sure I have reinvented an already existing standard python function somewhere. I'd like to know if my thinking is sound and the implementation makes sense.

Wouldn't itertools.arrangements be cool?


texts: Real time graph simulation of dice tossing

texts:
When tossing a dice many many time all numbers tend to appear the same number of times, but if the number of throws is small then some numbers may appear more or less often than others, even considerably if the sample size is small enough.

This program shows a updating in real time graph of SIDES bars (6 in default), each presenting how many times a number has appeared so far.

Please ignore that the numbers on the X axis are wrong, that is a minor bug-fix for later, all of the visualization is there.

My code feels a bit messy, please help in organization and simplification:

import random

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

SIDES = 6
HEIGHT = 100

def update_results(results):
    die_toss = random.randint(0, SIDES - 1)
    return [x + (1 if i == die_toss else 0) for i, x in enumerate(results)]

def plot_points(ps):
    plt.scatter(*zip(*ps))

def animate(frameno):
    global x
    x = update_results(x)
    n, _ = np.histogram(x, SIDES)
    n = x
    for rect, h in zip(patches, n):
        rect.set_height(h)
    print(x, max(x) / float(min(x)))
    return patches

if __name__ == "__main__":
    x = [ 1 for _ in range(SIDES) ]

    fig, ax = plt.subplots()
    n, bins, patches = plt.hist(x, SIDES, normed=1, facecolor='green', alpha=0.75)

    frames = 500
    ani = animation.FuncAnimation(fig, animate)

    axes = plt.gca()
    axes.set_ylim([0, HEIGHT])

    plt.show()

    plt.show()

    for i in range(100):
        plt.bar(range(SIDES), x)
        x =update_results(x)
        print(x)
        plt.show()
        plt.clf()


texts:
In my project I am using the ADR architecture, a branch of MVC.
In my actions (Controllers) I handle only data that comes from the request.
When there is a business rule that defines which status code I return, I do this treatment in my service.
Imagine this scenario:
When editing a user, I check if the user's email already exists, if it exists, I return an error informed to your message. This treatment is done in the service, and in these cases I get the error in it.
I would like to hear from you about my approach to, in some cases, the service layer returning the payload.
Action:
class CreateUserAction extends Action
{
    private $userService;

    /**
     * @param UserService $userService
     */
    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }

    public function handle(Request $request) : JsonResponse
    {
        $data = $request->getData();

        $payload = $this->userService->create($data, $user);

        return response()->json($payload->body, $payload->statusCode);
    }
}

Service:
class UserService extends BaseService
{
    private $userRepository;

    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function create(array $data) : object
    {
        if ($this->userRepository->findByEmail($data['email'])) {
            $this->setPayloadError(
                __('messages.user.contributor_email_already_exists'),
                Response::HTTP_BAD_REQUEST
            );
            return $this->getPayload();
        }

        $userCreated = $this->userRepository->create($data);

        $this->setPayload($userCreated, Response::HTTP_CREATED);
        return $this->getPayload();

    }
}
```