texts: Generating all combinations and permutations of a set of symbols

texts:
I am new to Python and want to have a "pythonic" coding style from the very beginning. Following is a piece of codes I wrote to generate all combinations and permutations of a set of symbols, e.g. abc or 123.  I mainly seek for suggestions on code style but comments on other aspects of codes are also welcome.

import random as rd
import math as m
def permutationByRecursion(input, s, li):
    if len(s) == len(input):
        li.append(s)
    for i in range(len(input)):
        if input[i] not in s:
            s+=input[i]
            permutationByRecursion(input, s, li)
            s=s[0:-1]

def combinationByRecursion(input, s, idx, li):
    for i in range(idx, len(input)):
        s+=input[i]
        li.append(s)
        print s, idx
        combinationByRecursion(input, s, i+1, li)
        s=s[0:-1]

def permutationByIteration(input):
    level=[input[0]]
    for i in range(1,len(input)):
        nList=[]
        for item in level:
            nList.append(item+input[i])
            for j in range(len(item)):
                nList.append(item[0:j]+input[i]+item[j:])
        level=nList
    return nList

def combinationByIteration(input):
    level=['']
    for i in range(len(input)):
        nList=[]
        for item in level:
            nList.append(item+input[i])
        level+=nList
    return level[1:]

res=[]
#permutationByRecursion('abc', '', res)
combinationByRecursion('abc', '', 0, res)
#res=permutationByIteration('12345')
print res
print combinationByIteration('abc')


texts: Higher order functions in Python using reduce technique

texts:
For the below query, show that both summation and product are
  instances of a more general function, called accumulate, with the
  following signature:

def accumulate(combiner, start, n, term):
    """Return the result of combining the first n terms in a sequence."""
    "*** YOUR CODE HERE ***"

  Accumulate takes as arguments the same arguments term and n as
  summation and product, together with a combiner function (of two
  arguments) that specifies how the current term is to be combined with
  the accumulation of the preceding terms and a start value that
  specifies what base value to use to start the accumulation. Implement
  accumulate and show how summation and product can both be defined as
  simple calls to accumulate:

def summation_using_accumulate(n, term):
    """An implementation of summation using accumulate.

    >>> summation_using_accumulate(4, square)
    30
    """
    "*** YOUR CODE HERE ***"

def product_using_accumulate(n, term):
    """An implementation of product using accumulate.

    >>> product_using_accumulate(4, square)
    576
    """
    "*** YOUR CODE HERE ***"

Below is the solution:

    from operator import mul, add

def accumulate(combiner, start, n, f):
    """Return the result of combining the first n terms in a sequence."""

    total = start           #Result of summation gets stored here
    i = 1                   #Initial value of sequence
    while i <= n:
        total = combiner(total, f(i))
        i = i + 1
    return total

def summation_using_accumulate(n, f):
    """An implementation of summation using accumulate.

    >>> summation_using_accumulate(4, square)
    30
    """
    return accumulate(add, 0, n, f)

def product_using_accumulate(n, f):
    """An implementation of product using accumulate.

    >>> product_using_accumulate(4, square)
    576
    """
    return accumulate(mul, 1, n, f)

def square(x):
    return mul(x, x)

print("product_using_accumulate: ",product_using_accumulate(4, square))
print("summation_using_accumulate: ",summation_using_accumulate(4, square))
print(accumulate(add, 0, 4, square))
print(accumulate(mul, 1, 4, square))

I have tested this code and looks good to me.

My questions:

Does the solution look incorrect in any aspect?
Any feedback on naming conventions?
Any feedback on coding style?


texts: Heap insertion and deletion Implementation using Python

texts:
I have implemented basic max heap insertion and deletion functions without recursion
# insertion
arr: [6,5,4,3,2,1]

# insert 7
arr: [7,5,6,3,2,1,4]
tree:

        7
    5       6
  3   2   1    4

# delete 7
arr: [6,5,4,3,2,1]
tree:

        6
    5       4
  3   2  1

My implementation
def insert(arr,ele):
    # bottom up
    n = len(arr)
    # insert into the n+1 position
    new_arr = arr.append(ele)
    i = n # last position
    while True:
        p_index = int((i-1)/2)
        # compare with the parent index
        if (arr[i] > arr[p_index]):
            # swap the elements
            arr[p_index], arr[i] = arr[i], arr[p_index]
            i = p_index
        else:
            # correct
            break
    return arr

# deletion
def delete(arr):
    # top down
    if not arr:
        return None
    # swap the last elment to root
    arr[0], arr[len(arr)-1] = arr[len(arr)-1], arr[0]
    item = arr.pop()
    n = len(arr)
    i = 0
    # comparing the children
    while True:
        # left/right child index
        lc_index = 2*i + 1
        rc_index = 2*i + 2
        # no chilren
        if lc_index > n-1:
            break
        # only has left child
        if lc_index == (n-1) and rc_index > n-1:
            if arr[lc_index] > arr[i]:
                arr[i], arr[lc_index] = arr[lc_index], arr[i]
            break
        else:
            if arr[lc_index] > arr[rc_index]:
                arr[i], arr[lc_index] = arr[lc_index], arr[i]
                i = lc_index
            else:
                arr[i], arr[rc_index] = arr[rc_index], arr[i]
                i = rc_index
    return item

These two functions works fine, but looks pretty cumbersome especially the delete function, any suggestions how to improve the code?


texts:
The following is a excerpt from a class that is supposed to represent a reflection of an object in a 3D world, like in a mirror.

After I started I discovered that mirroring is a property of an object, it is either mirrored, or it isn't. Multiple mirrors don't come up with unique objects but just keep flipping from one to the other, with differing rotations.

So with that in mind, how can I re-factor this class, to more suitably deal with the problem?

package au.id.rleach.efficientmultiblocks;

import org.spongepowered.api.util.Axis;

import java.util.EnumMap;
import java.util.LinkedHashSet;
import java.util.Set;

public class Reflexion {
    private final EnumMap<Axis, Boolean> map = new EnumMap<Axis,Boolean>(Axis.class);

    public Reflexion() {
        for(Axis x:Axis.values()){
            map.put(x, false);
        }
    }

    public Reflexion(Axis...axises){
        this();
        for(Axis x : axises){
            map.put(x,true);
        }
    }

    public Reflexion(Reflexion r, boolean x, boolean y, boolean z){
        //^ is xor
        map.put(Axis.X, x ^ r.map.get(Axis.X));
        map.put(Axis.Y, y ^ r.map.get(Axis.Y));
        map.put(Axis.Z, z ^ r.map.get(Axis.Z));
    }

    int getFlip(Axis x){
        return map.get(x) ? -1 : 1;
    }

    static Set<Reflexion> all(){
        return all(new Reflexion());
    }

    static Set<Reflexion> all(Reflexion r){
        Set<Reflexion> out = new LinkedHashSet<Reflexion>();
        //Loop over all values for each axis.
        boolean[] tf = {true, false};
        for(boolean x : tf){
            for(boolean y : tf){
                for(boolean z : tf){
                    out.add(new Reflexion(r, x, y, z));
                }
            }
        }
        return out;
    }
}


texts: Cron expression validator for Apache Quartz

texts:
Not too long ago, I had to create a cron expression for a route in Apache Camel. I had a bit of a struggle to find the right expression. So I made a small program to output the n next valid dates returned by the expression. I planned to add more feature like instead of making a blind Sysout, you could create a file with your dates.

In my application, a cron expression correspond to the definition of this class. It's use to fire an event for a Camel route. You will set a Quartz endpoint to your route and use a cron expression to express at which interval it should start. Some example :

  0 0/5 12-18 ? * MON-FRI

This cron expression translated to a more human format would be : every five minutes starting at 12pm (noon) to 6pm on weekdays. (this cron is taken from the quartz documentation).

For this particular cron, my program (with an numberOfdates set to 5) would output :

  Fri Sep 19 12:05:00 EDT 2014
  Fri Sep 19 12:10:00 EDT 2014
  Fri Sep 19 12:15:00 EDT 2014
  Fri Sep 19 12:20:00 EDT 2014
  Fri Sep 19 12:25:00 EDT 2014

The application is really basic. I take two arguments, the cron expression and the numbers of date you want outputted.

Feel free to cover any aspect. I had particular problem with the naming of my classes and variables. There isn't much code at the moment, but my naming and the way I verify arguments worry me a bit.

It's a public repo on GitHub

CronTester

import java.util.Date;
import java.util.List;

public class CronTester {

    /**
     * The application take two arguments :
     * The first argument is the cron expression surrounded by " : "* * * * * *"
     * The second argument is the number of dates you want to verify. It's a simple Integer.
     * @param args
     */
    public static void main(String[] args) {
        if(args.length > 2) {
            throw new IllegalArgumentException("You should only provide 2 arguments. \"[cronExpression]\" [numberOfDates]");
        } else if (args.length != 2) {
            throw new IllegalArgumentException("You need to provide 2 arguments in the following form : \"[cronExpression]\" [numberOfDates]");
        }

        final String expression = args[0];
        final int numberOfDates;

        try {
            numberOfDates = Integer.parseInt(args[1]);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("The second argument need to be a valid integer.");
        }

        final CronDateCreator dateCreator = new CronDateCreator(expression);
        List<Date> result = dateCreator.createValidTimeDatesFromNow(numberOfDates);

        for(Date expected : result) {
            System.out.println(expected);
        }

    }

}

CronDateCreator

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.quartz.CronExpression;

public class CronDateCreator {

    private CronExpression cron;

    public CronDateCreator(String cronExpressionRaw) {
        try {
            this.cron = new CronExpression(cronExpressionRaw);
        } catch (ParseException e) {
            throw new IllegalArgumentException("The cron expression supplied is not a valid cron expression.",e);
        }
    }

    public List<Date> createValidTimeDates(Date startingDate, int numberOfDates) {
        Date nextValidDate = cron.getNextValidTimeAfter(startingDate);
        List<Date> results = new ArrayList<>();

        for (int i = 0; i < numberOfDates; i++) {
            results.add(nextValidDate);
            nextValidDate = cron.getNextValidTimeAfter(nextValidDate);
        }

        return results;
    }

    public List<Date> createValidTimeDatesFromNow(int numberOfDates) {
        return createValidTimeDates(new Date(), numberOfDates);
    }

}


texts:
My application imports a CSV file and parses each row, turning it into an object in my code.

The speed for a 500,000 row x 68 column takes 2+ minutes to read. I've narrowed down the bottleneck to the part where the strings are being converted into their respective types using the converter I created. I need some pointers on how I can optimize my code.

This is the code I use to load:

public static void Load(object target, string[] fields, bool supressErrors)
{
    Type targetType = target.GetType();
    PropertyInfo[] properties = targetType.GetProperties();

    foreach (PropertyInfo property in properties)
    {
        object[] attributes = property.GetCustomAttributes(typeof(CSVPositionAttribute), false);

        if (attributes.Length > 0)
        {
            CSVPositionAttribute positionAttr = (CSVPositionAttribute)attributes[0];

            int position = positionAttr.Position;
            try
            {
                object data = fields[position];

                if (positionAttr.DataTransform != string.Empty)
                {
                    MethodInfo method = targetType.GetMethod(positionAttr.DataTransform);
                    data = method.Invoke(target, new object[] { data });
                }
                var prop = property.PropertyType;

                //bottleneck here:
                if (prop == typeof(string))
                {
                    property.SetValue(target, CheckAndConvert.CheckString(data), null);
                }
                else if (prop == typeof(int))
                {
                    property.SetValue(target, CheckAndConvert.CheckInt(data.ToString()), null);
                }
                else if (prop == typeof(double))
                {
                    property.SetValue(target, CheckAndConvert.CheckDouble(data.ToString()), null);
                }
                else if (prop == typeof(long))
                {
                    property.SetValue(target, CheckAndConvert.CheckLong(data.ToString()), null);
                }
                else if (prop == typeof(bool))
                {
                    property.SetValue(target, CheckAndConvert.CheckBool(data.ToString()), null);
                }

            }
            catch(Exception e)
            {
                if (!supressErrors)
                    throw;
            }
        }
    }
}

This is part of the code I use to convert each cell:

public class CheckAndConvert
{
    public static int CheckInt(string input)
    {
        int convertedInput = 0;
        double convertedInput2 = 0;

        if (int.TryParse(input, out convertedInput))
        {
            return convertedInput;
        }
        else if (double.TryParse(input, out convertedInput2))
        {
            return (int)convertedInput2;
        }
        else
        {
            return 0;
        }
    }
    public static double CheckDouble(string input)
    {
        double convertedInput = 0;
        int convertedInput2 = 0;
        if (double.TryParse(input, out convertedInput))
        {
            return convertedInput;
        }
        else if (int.TryParse(input, out convertedInput2))
        {
            return convertedInput2;
        }
        else
        {
            return 0;
        }
    }
    public static bool CheckBool(string input)
    {
        bool convertedInput = true;
        if (bool.TryParse(input, out convertedInput))
        {
            return convertedInput;
        }
        else
        {
            return true;
        }
    }
    public static string CheckString(object input)
    {
        if (input == null)
        {
            return "";
        }
        else
        {
            return input.ToString();
        }
    }

}


texts:
I am trying to check that a list of files are all images using functional programming.

Some actions I go through are asynchronous, so I have to wait for them to completely finish before passing to a new one.

const filteredFiles = ['favicon.ico', 'site.webmanifest', 'browserconfig.xml'];
const fileBuffers = await Promise.all(
    directory.files
        .filter(file => !filteredFiles.includes(file.path))
        // get a buffer containing the image file
        .map(async file => await file.buffer())
)
const everyFileIsImage = (await Promise.all(
    // check that this buffer has correct mime type
    fileBuffers.map(async buffer => await this.bufferIsImageFile(buffer))
)).every(isImage => isImage);

if (!everyFileIsImage) {
    throw new BadRequestException(`All files except ${filteredFiles} must be images`);
}

Here is the bufferIsImageFile method which is using the file-type library

private async bufferIsImageFile(buffer) {
    const type = await FileType.fromBuffer(buffer);

    return type !== undefined && type.mime.startsWith('image/');
}

I am not all satisfied by the piece of code. But I'm also not sure on how it could be improved.

What I'd like the most would be to avoid using those Promise.all, but is it even possible?

Maybe should I use a for loop instead?


texts: Updating an offset in a buffer after each read

texts:
I'm having a bit of a debate at work regarding when to replace numeric literals with variable names.

I have a function that reads data from a buffer and after each read, updates the offset so that next time, we read starting at the right offset.

function readMessage(data: Buffer, offset: number) {
    let firstLen = data.readInt32LE(offset);
    offset += 4;

    let firstPieceOfMessage = data.slice(offset, offset + firstLen).toString();
    offset += firstLen;

    let secondLen = data.readInt32LE(offset);
    offset += 4;

    let secondPieceOfMessage = data.slice(offset, offset + secondLen).toString();
    offset += secondLen;

    let finalMessage = firstPieceOfMessage + secondPieceOfMessage;
    return [finalMessage, offset];
}

The calling code calls this function in a loop:

let offset = 0;
while (offset < data.length) {
    let message;
    ([message, offset] = readMessage(data, offset));
    console.log(message);
}

A coworker made a comment that I should replace the 4 with a constant defined elsewhere.

My view is that since 4 is intimately-bound to the function readInt32LE, and the offset updating happens immediately after reading the 32 bits, it's more readable to keep the 4 and 32 next to each other.

Replacing 4 with a variable like numberOfBytesPerMessagePiece would jump out at me, because then I'll wonder "Wait, this would only work if that variable is set to 4, because that aligns with the function that I'm using above it. Is it actually set to that?"

If Node had a more general function readIntLE(offset, 4), then I would gladly replace 4 with a constant, but since there isn't, and we must use a function whose name contains a literal, it feels better to keep the literal 4 next to it.

Second, changing the constant to something else would necessarily break the code, since one would have to link that change with replacing readInt32LE with something more apt.

This is complicated by the fact that we use 4 in other places in this file (but not in other files), but almost all places (all but one) use it next to a similar function:

let buff = Buffer.alloc(4 + headerLen);
buff.writeInt32LE(someLength, 0);
buff.write(header, 4);

I'm thinking now that I could call this constant bytesIn32Bits = 4;. Is this worth the trouble?

Update:

This is one option I'm exploring right now:

function readLength(data: Buffer, offset: number): [number, number] {
    const len: number = data.readInt32LE(offset);
    offset += 4;

    return [len, offset];
}

function readData(data: Buffer, offset: number, length: number): [Buffer, number] {
    let msg: Buffer = data.slice(offset, offset + length);
    offset += length;

    return [msg, offset];
}

This will at least allow me to get rid of the offset updates in the first example.

function readMessage(data: Buffer, offset: number) {
    let firstLen: number;
    ([firstLen, offset] = readLength(data, offset));

    let firstPieceOfMessage: string;
    ([firstPieceOfMessage, offset] = readData(data, offset, firstLen));

    let secondLen: number;
    ([secondLen, offset] = readLength(data, offset));

    let secondPieceOfMessage : string;
    ([secondPieceOfMessage, offset] = readData(data, offset, secondLen));

    let finalMessage = firstPieceOfMessage + secondPieceOfMessage;
    return [finalMessage, offset];
}

I'm not convinced that that looks any nicer though.


texts: Divide decimal by range of fractions, and then convert the fraction that is closest to a whole number to a mixed fraction

texts:
My program will divide the decimal (\$30.0575\$) by a range of fractions (\$\frac{1}{1}, \frac{1}{2}, \frac{1}{4}, \dots, \frac{1}{48})\$ leaving me with list of improper fractions that look like this:

\$\frac{1}{1} * 30.0575\$
\$\frac{1}{2} * 60.115\$
\$\frac{1}{3} * 90.1725\$
\$\dots\$
\$\frac{1}{48} * 1442.76\$

My program will then "pick out" the improper fraction that contains the decimal that is closest to a whole number. It will finally convert the improper fraction that is closest to a whole number into a mixed fraction.

How can I make my program more readable?
Are there any "shortcuts" I could implement that would reduce the lines of code used?
How can I overall optimize my code so it completes the same task in a more efficient way, while still keeping readability?

private void FractionsForm_Load(object sender, EventArgs e)
        {
            var myDecimal = 30.0575;

            var results = new List<double>();

            for (double i = 1; i < 49; i++)
            {
                var fraction = 1 / i;
                var result = myDecimal / fraction;
                results.Add(result);
                Console.WriteLine("1/{0} * {1}", i, result);
            }

            WriteLineSeparator();

            var remainders = new List<double>();

            foreach (var result in results)
            {
                var roundedResult = Math.Round(result);
                var remainder = roundedResult - result;
                remainders.Add(Math.Abs(remainder));
            }

            var mostAccurateRemainder = remainders.Min();
            var mostAccurateRemainderIndex = remainders.IndexOf(mostAccurateRemainder);
            var fractionDenominator = mostAccurateRemainderIndex + 1;

            Console.WriteLine("1/{0} * {1}", fractionDenominator, results[mostAccurateRemainderIndex]);

            WriteLineSeparator();

            var integerPart = Convert.ToInt32(myDecimal);
            var integralPart = myDecimal - Math.Truncate(myDecimal);

            Console.WriteLine("{0} {1}/{2}", integerPart, Convert.ToInt32(integralPart * fractionDenominator),
                fractionDenominator);
        }

        private static void WriteLineSeparator()
        {
            Console.WriteLine(string.Empty);
            Console.WriteLine("--------------------------------------------------");
            Console.WriteLine(string.Empty);
        }

        /*

            1/1 * 30.0575
            1/2 * 60.115
            1/3 * 90.1725
            1/4 * 120.23
            1/5 * 150.2875
            1/6 * 180.345
            1/7 * 210.4025
            1/8 * 240.46
            1/9 * 270.5175
            1/10 * 300.575
            1/11 * 330.6325
            1/12 * 360.69
            1/13 * 390.7475
            1/14 * 420.805
            1/15 * 450.8625
            1/16 * 480.92
            1/17 * 510.9775
            1/18 * 541.035
            1/19 * 571.0925
            1/20 * 601.15
            1/21 * 631.2075
            1/22 * 661.265
            1/23 * 691.3225
            1/24 * 721.38
            1/25 * 751.4375
            1/26 * 781.495
            1/27 * 811.5525
            1/28 * 841.61
            1/29 * 871.6675
            1/30 * 901.725
            1/31 * 931.7825
            1/32 * 961.84
            1/33 * 991.8975
            1/34 * 1021.955
            1/35 * 1052.0125
            1/36 * 1082.07
            1/37 * 1112.1275
            1/38 * 1142.185
            1/39 * 1172.2425
            1/40 * 1202.3
            1/41 * 1232.3575
            1/42 * 1262.415
            1/43 * 1292.4725
            1/44 * 1322.53
            1/45 * 1352.5875
            1/46 * 1382.645
            1/47 * 1412.7025
            1/48 * 1442.76

            --------------------------------------------------

            1/35 * 1052.0125

            --------------------------------------------------

            30 2/35

        */


texts:
Can't seem to find one, so trying to build a very simple but fast implementation. Thought I would post on SO for review/feedback, and so that others can just copy/paste for their own use.

I'm using a Dictionary and LinkedList, with a non-granular lock.  Basic benchmark included below:

public class LRUDictionary<TKey,TValue> : IDictionary<TKey,TValue>
{
    private Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>_dict=
        new Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>();

    private LinkedList<KeyValuePair<TKey, TValue>> _list =
        new LinkedList<KeyValuePair<TKey, TValue>>();

    public int Max_Size { get; set; }

    public LRUDictionary(int maxsize)
    {
        Max_Size = maxsize;
    }

    public void Add(TKey key, TValue value)
    {
        lock (_dict)
        {
            LinkedListNode<KeyValuePair<TKey, TValue>> node;

            if (_dict.TryGetValue(key, out node))
            {
                _list.Remove(node);
                _list.AddFirst(node);
            }
            else
            {
                node = new LinkedListNode<KeyValuePair<TKey, TValue>>(
                new KeyValuePair<TKey, TValue>(key, value));

                 _dict.Add(key, node);
                _list.AddFirst(node);

            }

            if (_dict.Count > Max_Size)
            {
                var nodetoremove = _list.Last;
                if (nodetoremove != null)
                    Remove(nodetoremove.Value.Key);
            }
        }

    }

    public bool Remove(TKey key)
    {
        lock (_dict)
        {
            LinkedListNode<KeyValuePair<TKey, TValue>> removednode;
            if (_dict.TryGetValue(key, out removednode))
            {
                _dict.Remove(key);
                _list.Remove(removednode);
                return true;
            }

            else
                return false;
        }
    }

    public bool TryGetValue(TKey key, out TValue value)
    {
        LinkedListNode<KeyValuePair<TKey, TValue>> node;

        bool result = false;
        lock (_dict)
            result = _dict.TryGetValue(key, out node);

        if (node != null)
            value = node.Value.Value;
        else
            value = default(TValue);

        return result;
    }

  [rest of IDictionary not implemented yet]

  }

Benchmark:

class Program
{
    static Random rand = new Random();
    static void Main(string[] args)
    {
        var lruspace = 50;
        var setsize = 100;
        var iterations = 1000 * 1000;
        var lrucache = new LRUDictionary<int, int>(lruspace);
        var watch = new Stopwatch();

        watch.Start();

        Parallel.For(0, iterations, (i) =>
        {
            lrucache.Add(rand.Next(setsize), 0);
            lrucache.Add(rand.Next(setsize), 0);

            lrucache.Remove(rand.Next(setsize));
            lrucache.Add(rand.Next(setsize), 0);

            lrucache.Remove(rand.Next(setsize));
            lrucache.Remove(rand.Next(setsize));

            lrucache.Add(rand.Next(setsize), 0);
            lrucache.Remove(rand.Next(setsize));
            lrucache.Add(rand.Next(setsize), 0);
            lrucache.Add(rand.Next(setsize), 0);
            lrucache.Add(rand.Next(setsize), 0);
        });

        Console.WriteLine(watch.ElapsedMilliseconds);
        Console.ReadLine();

    }
}

Output:

2592ms

Is this the best way to go? Any obvious improvements?


texts: Recursing function to create dir in python

texts:
I am trying to write a small function to safely create dir until dir until full path of file exists. I'm trying to do it in a recursing function and would love to get some feedback.

def makedir(filepath: str) -> bool:
    if os.path.exists(os.path.dirname(filepath)):
        return
    os.makedirs(os.path.dirname(filepath), exist_ok=True)
    makedir(filepath)

makedir('/a/b/c/d/x.text')
#should create a then b then c then d
makedir('/a/b/c/e/y.text')
#should create e only since a, b,c already exist


texts: Could this PHP Facebook class be any more OOP-ified?

texts:
I have this Facebook class and I'm wondering if the OOP nature of it could be improved at all?

(GitHub project here):

<?php

class Facebook {

    private $baseUrl = 'https://graph.facebook.com/';

    public function basicInfo($username){

        if($username !== ''){
       $url = $this->baseUrl . $username;
      }
      if($url !== ''){
            $data = $this->__apiCall($url);
      }
      return $data;

    }

    public function userProfilePicture($username, $size = 'square'){

        if($username !== ''){
       $url = $this->baseUrl . $username . '/picture?type=' . $size;
      }
      return $url;

    }

    public function searchPublicPosts($query){

        if($query !== ''){
       $url = $this->baseUrl . 'search?q=' . urlencode($query) . '&type=post';
      }
      if($url !== ''){
            $data = $this->__apiCall($url);
      }
      return $data;

    }

    public function searchPages($page){

        if($page !== ''){
       $url = $this->baseUrl . 'search?q=' . urlencode($page) . '&type=page';
        }

        if($url !== ''){
       $data = $this->__apiCall($url);
      }
      return $data;

    }

    public function searchEvents($event){

        if($event !== ''){
       $url = $this->baseUrl . 'search?q='.urlencode($event).'&type=event';
      }
      if($url !== ''){
            $data = $this->__apiCall($url);
      }
      return $data;

    }

    private function __apiCall($url){

        $raw = file_get_contents($url);
        $json = json_decode($raw, true);
        return $json;

    }

}


texts: Using model view presenter (MVP) in C# code

texts:
I'm a beginner to Model-View-Presenter pattern and I'm finding a way to use it in a sample application

In my C# winforms application has a Employee Class and it has properties like EmployeeID,Name, Address, Designation etc. Also it has behaviors like viewEmployee(), AddNewEmployee(), PromoteEmployee() etc.

Could you please suggest how these things are organized in MVP pattern?
I have several entity classes in my project like Employee, Client, Attendance, Salary etc. So should I make separate DataService and Presenter classes for each one?

My current understanding is like this...

Implementing ViewEmployee()----------

Class Employee
{
    public string EmployeeID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Designation { get; set; }
}

Class EmployeePresenter
{
   public void ViewEmployee(string employeeID, frmEmployeeDetails _form)
   {
     Employee Emp= EmloyeeDataService.GetEmployeeData(employeeID);
     _form.txtName=Emp.Name;
     _form.txtAddress=Emp.Address;
     _form.txtDesignation=Emp.Designation;
   }
}

Class EmployeeDataService
{
    public static Employee GetEmployeeData(String employeeID)
    {
      //Get data from database
      // Set Properties of Employee
      //Return Employee
    }
}

Partial Class frmEmployeeDetails : Form
{
    btnViewEmployee_Click() //Button Event
    {
      EmployeePresenter.ViewEmployee(txtEmployeeID.text,this);
    }
}


texts: Minimum perfect squares needed to sum up to a target

texts:
I'm trying to solve this problem

  Given a positive integer n, find the least number of perfect square
  numbers (for example, 1, 4, 9, 16, ...) which sum to n.

I've come up with a solution that works correctly but times out on large inputs:

from collections import defaultdict
class Solution:
    def numSquares(self, n: int) -> int:
        coins = []
        for i in range(1, n+1):
            if i**2>n:
                break
            coins.append(i**2)
        min_coins_to_make = defaultdict(lambda :float("inf"))
        min_coins_to_make[0] = 0
        for coin in coins:
            if coin > n:
                break
            for target in range(coin, n+1):
                min_coins_to_make[target] = min(min_coins_to_make[target], 1+min_coins_to_make[target-coin])
        if min_coins_to_make[target] == float("inf"):
            return 0
        return min_coins_to_make[target]

How do I optimize it in terms of time and space complexity?

https://leetcode.com/problems/perfect-squares/


texts: Producing and comparing maximum sub array sum algorithms

texts:
This is an exercise in implementing the maximum sub-array sum problem.

It asks for several solutions of complexity:

\$O(n)\$
\$O(n \log n)\$
\$O(n^2)\$
\$O(n^3)\$

For an additional challenge I completed it using Python.

import random
import timeit

#random array generator
def generate_array(item_count, lower_bound, upper_bound):
    number_list = []
    for x in range(1, item_count):
        number_list.append(random.randint(lower_bound, upper_bound))
    return number_list

#cubic brute force O(n^3)
def max_subarray_cubic(array):
    maximum = float('-inf')
    for i in range(1, len(array)):
        for j in range(i, len(array)):
            current_sum = 0
            for k in range(i, j):
                current_sum += array[k]
            maximum = max(maximum, current_sum)
    return maximum

#quadratic brute force O(n^2)
def max_subarray_quadratic(array):
  maximum = float('-inf')
  for i in range(0, len(array)):
    current = 0
    for j in range(i, len(array)):
       current += array[j]
       maximum = max(current, maximum)
  return maximum

#divide and conquer O(n*lg(n))
def max_cross_sum(array, low, mid, high):
  left_sum = float('-inf')
  sum_ = 0
  for i in range(mid, low, -1):
    sum_ += array[i]
    left_sum = max(left_sum, sum_)

  right_sum = float('-inf')
  sum_ = 0
  for i in range(mid + 1, high):
    sum_ += array[i]
    right_sum = max(right_sum, sum_)
  return left_sum + right_sum

def max_subarray_div_conquer(array, low, high):
  if low == high:
    return array[low]
  else:
    mid = (low + high) / 2
    return max(max_subarray_div_conquer(array, low, mid),
               max_subarray_div_conquer(array, mid + 1, high),
               max_cross_sum(array, low, mid, high))

#Kadane's algorithm O(n)
def max_subarray_kadane(array):
    current = maximum = array[0]
    for x in array[1:]:
        current = max(x, current + x)
        maximum = max(maximum, current)
    return maximum

#to facilitate timing each algorithm
def function_timer(function, array, policy):
    start_time = timeit.default_timer()
    if policy == "divide and conquer":
        print("Maximum sub sum for the %s algorithm: %s"
            % (policy, function(array, 0, len(array) - 1)))
    else:
        print("Maximum sub sum for the %s algorithm: %s" % (policy, function(array)))
    print("Running Time: %s seconds.\n" % (timeit.default_timer() - start_time))

magnitude = input('enter vector size: ')
number_list = generate_array(magnitude, -10, 10)

function_timer(max_subarray_cubic, number_list, "cubic")
function_timer(max_subarray_quadratic, number_list, "quadratic")
function_timer(max_subarray_div_conquer, number_list, "divide and conquer")
function_timer(max_subarray_kadane, number_list, "kadane")

I would like:

To know if this is Pythonic? Am I accurately following conventions?
A general review on the accuracy of the algorithms. To the best of my knowledge I completed the requirements, but just in case. Focusing on the divide and conquer algorithm as it heavily differs and the cubic solution, it's surprisingly difficult to think about how to solve something poorly.
Feedback on the way I measure running time. I gave myself a means to run tests but how effective is it? How reliable are the results?


texts:
I have two seperate calls that returns a .csv file. I need to extract a couple of headers from the files depending on which one is called. The headers does not always sit in the same index, and the CourseId name changes to Asset_ID in the one call.

How can I refactor the code to make it more maintainable?

Also, I think the naming is not really good.

public static class CsvHeader
        {
            public struct Index
            {
                public string Email { get; set; }
                public string CompletionDate { get; set; }
                public string CourseId { get; set; }
            }
            public static Index GetCsvHeaderIndex(string[] headers)
            {
                string emailIndex = null;
                string completionDateIndex = null;

                var email = headers.FirstOrDefault(_ => _.Contains("Email"));
                var completionDate = headers.FirstOrDefault(_ => _.Contains("Completion"));
                var courseId = headers.FirstOrDefault(_ => _.Contains("CourseID"));

                if (!string.IsNullOrEmpty(email)) emailIndex = headers.First(_ => _.Contains("Email")).Split('(', ')')[1]; /*3*/
                if (!string.IsNullOrEmpty(completionDate)) completionDateIndex = headers.First(_ => _.Contains("Completion")).Split('(', ')')[1]; /*30*/
                var courseIdIndex = string.IsNullOrEmpty(courseId) ?
                    headers.First(_ => _.Contains("Asset_ID")).Split('(', ')')[1] :
                    headers.First(_ => _.Contains("CourseID")).Split('(', ')')[1];

                return new Index
                {
                    Email = emailIndex,
                    CompletionDate = completionDateIndex,
                    CourseId = courseIdIndex
                };
            }
        }


texts: Creating a generic function for objects of different classes

texts:
How might I refactor this to get rid of all the if-else?

  def self.dispatches_for(object)
    scope = Dispatch.asc(:days)
    if object.class == Habit
      scope.where(:habit=>object).map{|d|d}
    elsif object.class == User
      scope.where(:coach=>object).map{|d|d}
    elsif object.class == Content
      scope.where(:content=>object).map{|d|d}
    end
  end


texts:
I quite often find myself checking whether a given value is present in a given, possibly nested, container. For example, is int val present in the nested container vector<vector<int>> values? To me this looks like a good opportunity to practice with template functions while also cleaning my code. I wrote the following recursive template function for this.

Do you have any suggestion to improve this? E.g, can it be shortened, can it be made more readable or more efficient, is the concept of namespaces correctly used, or should I maybe use a different coding style?

Note: I use gco as an abbreviation for General Container Operations.

// gco.h
#pragma once

#include <algorithm>

namespace bs
{
  namespace gco
  {

    /*
     * This function checks whether 'val' is found in the
     * given container 'source'. The function searches multiple
     * levels deep until it finds the same type as 'val'
     */

    template<typename T1, template <typename> typename Container, typename T2>
    bool contains (Container<T1> const &source, T2 const &val)
    {
      if constexpr (std::is_same<T1, T2>::value)
        return std::find(std::cbegin(source), std::cend(source), val) != std::cend(source);

      else
      {
        for (auto const &el: source)
          if (contains(el, val))
            return true;

        return false;
      }
    }
  }
}

EDIT: minimum working example

#include "./gco.h"
#include <vector>

using namespace std;
using namespace bs;

int main()
{
  vector<int> source_1 = {1, 2, 3, 4};

  vector<vector<int>> source_2 = {{1,2}, {3,4}};

  /*
   * 1) search a single int in a vector
   * 2) search a single int in a nested vector
   * 3) search a vector in a nested vector
   *
   * The following should print 1 0 1 0 1 0
   */

  cout << gco::contains(source_1, 4) << endl
       << gco::contains(source_1, 5) << endl

       << gco::contains(source_2, 4) << endl
       << gco::contains(source_2, 5) << endl

       << gco::contains(source_2, vector<int>({1,2})) << endl
       << gco::contains(source_2, vector<int>({1,3})) << endl;
}


texts: Convert Simple C# Console>Service to perform repeated API calls and file system actions

texts:
I was sent here from StackOverflow, as it was indicated that the quality of my current approach may have been questionable. I'm attempting to transform a simple console application so that it may be used as a service using a nested Service class (relevant code below). The intent is to create a service to perform the actions within the Run method more-or-less at a regular interval. I'm new to .NET, so please bare with me if there are obvious flaws in my implementation.

In short, the Service's OnStart calls my own Start method once, which creates a timer. Inside the timer, I'm creating an instance of the Program class, and performing the Run method till it finishes. I believe this is a valid implementation of what I want that doesn't leave resources outstanding, although I am unsure whether I should dispose of the Prg object at the end of CallTimer. Part of what the Run method does is build a dictionary of actions on the file system that were unsuccessful so that they may be attempted again in the next run.

I'm a bit green and not terribly confident that I'm doing things correctly, but I'm attempting to get up to speed as quickly as possible, so any assistance is appreciated. I can provide additional details if needed.

partial class Program{
    static object timerLck = new object();

    public class Service : ServiceBase{
        public Service(){
            ServiceName = Program.ServiceName;
        }
        protected override void OnStart(string[] args){
            Program.Start(args);
        }
        protected override void OnStop(){
            Program.Stop();
        }
    }

    static void Main(string[] args){
        if (!Environment.UserInteractive)
            using (var service = new Service())
                ServiceBase.Run(service);
        else{
            Start(args);
            Stop();
        }
    }

    private static void Start(string[] args){
        Timer t = new Timer(CallTimer, null, 0, 50000);
        Console.ReadKey();
    }

    private static void Stop(){
        //log service stopped
    }

    static void CallTimer(object state){
        bool Lock = false;
        Dictionary<string, Metadata> PreviousErrors = new Dictionary<string, Metadata>();
        try{
            Lock = Monitor.TryEnter(timerLck);
            if (Lock){
                Program Prg = new Program()
                var task = Task.Run(()=>Prg.Run(PreviousErrors));
                PreviousErrors = task.Result;
            }
        }
        finally{
            if (Lock) Monitor.Exit(timerLck);
        }
    }

    //Perform the repeated actions here
    private async Task<Dictionary<string, Metadata>> Run(Dictionary<string, Metadata> previousErrors){
        Dictionary<string, Metadata> d = new Dictionary<string, Metadata>();
        //...
        return d;
    }
}


texts: Chaining asynchronous calls to update UI

texts:
In an app the UI is updated from different threads. To queue this, I have created a utility class

public class AsyncChainedActions
{
    private Task _lastTask;
    public AsyncChainedActions()
    {
        _lastTask = Task.Run(() => { });
    }

    public void AddToAsyncChain(Action action, [CallerMemberName] string
     caller = null)
    {
        _lastTask = _lastTask.ContinueWith(o =>
        {
            try
            {
                action();
            }
            catch (Exception ex)
            {
                PublishError($"process {caller} message
              from service", ex);
            }
            o.Dispose();
        });
    }
}

util class is used as below

public class UpdateManager
{

  public ObservableCollection<Person> Persons{get;set;}//bound to a data
  //grid
  public UpdateManager()
 {
   Event1.Subscribe(Event1Update);
   Event2.Subscribe(Event2Update);

 }

 private void Event1Update(Person person)
 {
  _asyncChainedActions.AddToAsyncChain(() =>
  {
     if(NotValidUpdate(person)) return;

     _updateUi.ExecuteOnMainDispatcher(() =>
   {
     var update = Persons.FirstOrDefault(x => x.Id == person.Id );
     if(update!=null)
     {
       update.Name = person.Name;
        update.Age= person.Age;
       update.Address= person.Address;
    }
   });
 });
}

}

The events sometimes happens many times a second. In certain times the values updated on the Person object is not reflected in the UI grid. I confirm the value is indeed updated in the object, but it is just that it is not  reflected in the UI. It happens only sometimes. I think it is something to do with the dispatcher updates happening in the chain adn binding delays.

Do you see any issue with the async chain approach?


texts:
I've got a module I use to log around functions that performs external requests.

# Functions to track when a block begins and ends
module LogAround

  # log at begin and end of a given block
  # with a mesage and the given params
  def log_around(message, *args)
    start_time = Time.now
    Rails.logger.info "#{message}(#{args.inspect}) - start"

    result = yield

  ensure
    end_time = Time.now - start_time
    Rails.logger.info "#{message}(#{args.inspect}) - end (#{end_time}s)"

    result
  end
end

This module is used in this way:

class Wrapper
  include LogAround
  # TODO: log_around :get_artist
  alias_method :_orig_get_artist, :get_artist

  # log the external request
  def get_artist(*args)
    log_around 'Discogs::Wrapper.get_artist', *args do
      _orig_get_artist *args
    end
  end
end

This solution is much closer to what I want compared with what I had before, but ideally what I'm looking for is a function in LogAround that could be used in this way

# this class is already defined by Discogs
# and this is a customization
class Wrapper
  include LogAround
  log_around :get_artist
end

and provides the same (or better params list) output, which is:

Discogs::Wrapper.get_artist(["pink floyd"]) - start
Discogs::Wrapper.get_artist(["pink floyd"]) - end (1.919805308s)


texts: Determine if requested documents exist and if they do, whether they match requested revision number

texts:
Is there a better way than using 2 for loops and 2 if statements deep?

jsfiddle:

https://jsfiddle.net/bobbyrne01/bmnk9bLz/

Code:

var documentsInDatabase = [{
  id: '1',
  revision: '1'
}, {
  id: '2',
  revision: '1'
}, {
  id: '3',
  revision: '1'
}];

// incorrect revision of document with id of 1, and non-existent document of id 4
var requestedDocuments = [{
  id: '1',
  revision: '2'
}, {
  id: '4',
  revision: '1'
}];

var result = {
  ids_not_found: [],
  revision_mismatches: []
};

// 4 nested blocks deep
for (var i = 0; i < documentsInDatabase.length; i++) {
  for (var j = 0; j < requestedDocuments.length; j++) {
    if (documentsInDatabase[i].id === requestedDocuments[j].id) {
      if (documentsInDatabase[i].revision !== requestedDocuments[j].revision) {
        result.revision_mismatches.push(requestedDocuments[j].id);
      }

      requestedDocuments.splice(j, 1);
      break;
    }
  }
}

for (var l = 0; l < requestedDocuments.length; l++) {
  result.ids_not_found.push(requestedDocuments[l].id);
}

document.getElementById('container').innerHTML = JSON.stringify(result, null, 2);


texts: Custom indexeddb modules while trying to maintain the functional paradigm as much as possible

texts:
I'm a Web Development student, and I just started learning indexeddb a little while ago. At present my teacher hasn't taught us Promises, and I'm not really sure he plans to. So, I took the initiative and learned them myself. But as my teacher doesn't know or isn't teaching Promises, I wanted help reviewing my code to ensure that I am using best practices and that my is clean and well written.

Also, and the thing that I'm more focused on, is using the functional paradigm. When I started my degree, I made a point of learning it along the way. But now that I have to deal with databases and explicit stateliness I'm a bit at a loss. I did my best to maintain referential transparency and purity, but there's only so much I could do. I'd like to learn the functional approach to interacting with databases and the outside world in general.

The below code is functioning to the best of my knowledge. I coded it recently for my personal use (and practice), and it has passed all of my tests. But I haven't used it for an actual project yet, so I'm sure it has shortcomings.

returns a promise for an open link to the database:

function getDb(databaseName, version, upgradeDb) {
  return new Promise(function(resolve, reject) {
    const request = indexedDB.open(databaseName, version);
    request.onupgradeneeded = function(e) {
      if (upgradeDb) {
        /*
        This was really awkward. This whole function is dependent on the state
        of my database. Would it be better to use createDb and updateDb functions
        and then use this to only return the database?
        */
        upgradeDb(e.target.result);
        resolve(e.target.result);
      }
    }

    request.onsuccess = function(e) {
      resolve(e.target.result);
    };

    request.onerror = function(e) {
      reject(console.log("error"));
    }
  });
}

Short and sweat. More readable for me:

async function getObjectStore(db, objectStore, permissions) {
  return (await db).transaction([objectStore], permissions).objectStore(objectStore);
}

This one isn't strictly necesarry. And it'd be easier to just use objectStore.add() maybe. But I like it. Also, databases. State. Grr. What is a good way to manage I/O and stateliness when using the functional approach?:

async function addEntry(objectStore, object) {
  (await objectStore).add(object);
}

same as above:

async function deleteEntry(objectStore, keyRange) {
  (await objectStore).delete(keyRange);
}

This feels more awkward than maybe it should. It would be simpler to declare this as an async function and use await, but I don't know how to utilize resolve with that.:

function getEntries(objectStore, keyRange) {
  return new Promise(function(resolve, reject) {
    const request = (objectStore).then(x => x.getAll(keyRange));
    request.then(x => x.onsuccess = function(e) {
      resolve(e.target.result);
    });
  });
}

same as above:

function getEntry(objectStore, keyRange) {
  return new Promise(function(resolve, reject) {
    const request = (objectStore).then(x => x.get(keyRange));
    request.then(x => x.onsuccess = function(e) {
      resolve(e.target.result);
    });
  });
}

So this. I wanted it to be able to handle both inline and outline objectStore. This isn't really the most clean, because indexKey could be an object or a value. But I don't have the advantage of type declarations that I might have in other languages. It works for me, but is there a better solution?:

async function updateEntry(objectStore, indexKey, object) {
  if (typeof indexKey === Object) {
    const indexValue = Object.keys(indexKey)[0];
    const keyValue = indexKey[indexValue];
    const newObject = Object.assign({}, object, indexKey);
    const request = (await objectStore).get(keyValue);
    request.onsuccess = async function(e) {
      (await objectStore).put(newObject);
    };
  } else {
    const request = (await objectStore).get(indexKey);
    request.onsuccess = async function(e) {
      (await objectStore).put(object, indexKey);
    };
  }
}


texts: Finding next perfect number - brute force

texts:
A “perfect number” is defined as a number equal to the sum of all its factors less than itself. For example, the first perfect number is 6, because its factors are 1, 2, 3, and 6, and 1+2+3=6. The second perfect number is 28, because 1+2+4+7+14=28. What is the third perfect number? Write a procedure (next-perf n) that tests numbers starting with n and continuing with n+1, n+2, etc. until a perfect number is found. Then you can evaluate (next-perf 29) to solve the problem. Hint: you’ll need a sum-of-factors subprocedure.
[Note: If you run this program when the system is heavily loaded, it may take half an hour to compute the answer! Try tracing helper procedures to make sure your program is on track, or start by computing (next-perf 1) and see if you get 6.]

Source
I am aware of Euclid's algorithm for solving this problem, but with the "n+1,n+2" part of the problem statement I think I shouldn't do that. So I did it in a brute force way.
(define (nextPerf n)
    (define (sumOfFactors a)
        (cond ((= n a) 0)
            ((= (remainder n a) 0) (+ a (sumOfFactors (+ a 1))))
        (else (sumOfFactors (+ a 1)))))
    (if (= (sumOfFactors 1) n) n
        (nextPerf (+ n 1))))

Is this good code? How can I make it better?


texts:
The main idea is, I have a struct and I will get a struct field as a string from another function, which I shall increment its value by 1.
Below is the code I used and I think it is memory consuming.
How can I improve it? Is there a better way than the reflection from the start?
Thanks
package main
import (
    "fmt"
    "reflect"
)

func main() {

    type chrinfo struct {

    Size0_50    int
    Size50_100  int
    Size100_1000    int
    Size1000_10000  int
    Size10000   int
    }

    mychr := chrinfo{}
    n := "Size1000_10000"

    y := reflect.ValueOf(&mychr).Elem().FieldByName(n)
    reflect.ValueOf(&mychr).Elem().FieldByName(n).SetInt(int64(y.Interface().(int))+1)

    fmt.Println(mychr, y)
}


texts:
I'd like feedback on the class below, from the perspective of wanting to write professional code that I would be paid to create. I would appreciate comments on details such as commenting, naming and layout as well as the actual functionality.

The code is a class which takes two arguments (directory and extension) and searches the directory for instances of files with the given extension.

The context is of me practicing writing PHP with a view to getting a job doing so. There is the possibility of "unknown unknowns" implied in this question.

<?php
/**
 * Filters a directory by file-type
 */
class DirectoryFilter{

  /**
   * Returns a list of files in a given directory,
   * filtered by the extension of the files
     *
   * @param string $dirname
   * @param string $extension
   *
   * @return array
   */
    public function filter(string $dirname, string $extension){

        // store results in an array
        $results = [];

        // set path
        $path = __dir__ . "/$dirname";

        // check directory exists
        if(is_dir(($path))){

            foreach(glob("$path/*.*") as $filename) {
                if(pathinfo($filename, PATHINFO_EXTENSION) == $extension){
                    array_push($results, $filename);
                }
            }

            return $results;
        }

        // Directory not found
        return false;
    }
}

$test = new DirectoryFilter();
print_r ($test->filter('testdir', 'php'));


texts:
I wrote this in the last hour because I was bored.  I was hoping I could get some feedback on this.  It is a function that returns the price of a bitcoin and whether you should buy or sell it. I am thinking of setting it up as a function within a chat bot to spice up the chat a little.

import urllib2
import random
import json

def bitcoin(currency, amt = 1):
    url = "https://api.coindesk.com/v1/bpi/currentprice.json"
    request = urllib2.Request(url)
    response = urllib2.urlopen(request)
    the_page = response.read()
    data = json.loads(the_page)
    if currency in ["USD","US","dollar","$"]:
        conversion = data['bpi']['USD']['rate_float']
        symbol = "USD"
    elif currency in ["EUR","EU","euro","€"]:
        conversion = data['bpi']['EUR']['rate_float']
        symbol = "EUR"
    elif currency in ["GBP","GB","UK","pound","£"]:
        conversion = data['bpi']['GBP']['rate_float']
        symbol = "GBP"
    else:
        stop("Currency not recognized.")
    advice = random.choice(["It's so LOW!!!!!!! \r\nBuy!!! Buy!!! Buy!!!!!","It's so HIGH!!!!!! \r\nSell!!! Sell!!! Sell!!!!!"])
    return "{0} Bitcoin = {1} {2} \r\n{3}".format(amt,conversion * amt, symbol, advice)


texts:
I have below coded a class that loads information from a file that I select. The file then loads the content of that file in the INI format.

The INI format usually works when each line contains key=value and then each line is split by the  = character in the code. It also contains a method for getting the item by key from the dictionary of stored items previously loaded from the file. I wondered if anyone could help me out in finding any way to improve this?

I think its pretty well coded in my eyes, but of course there is always room for improvement.

namespace Hariak_Emulator.Emulator.Core.Config
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using NLog;
    using Utilities;

    internal sealed class ConfigManager : IDisposable
    {
        private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();

        private Dictionary<string, string> _configItems;
        private string _configFile;

        public ConfigManager()
        {
            _configItems = new Dictionary<string, string>();
            _configFile = "assets/config/hariak_config.ini";

            LoadConfig();
        }

        private void LoadConfig()
        {
            try
            {
                if (!File.Exists(_configFile) || Utilities.IsFileLocked(new FileInfo(_configFile)))
                {
                    Logger.Error("Either your config file couldn't be found, or its open somewhere else.");

                    Console.ReadKey(true);
                    Environment.Exit(0);
                }

                _configItems = File.ReadLines(_configFile).Where(IsConfigurationLine).Select(line => line.Split('=')).ToDictionary(line => line[0], line => line[1]);
            }
            catch (Exception exception)
            {
                Logger.Fatal("Error while loading config: " + exception.Message);
                Logger.Fatal(exception.StackTrace);

                Console.ReadKey(true);
                Environment.Exit(0);
            }
        }

        private static bool IsConfigurationLine(string line)
        {
            return !line.StartsWith("#") && line.Contains("=");
        }

        internal string GetConfigValueByKey(string key)
        {
            string value;

            if (!_configItems.TryGetValue(key, out value))
            {
                Logger.Warn("Missing configuration key `" + key + "`");
            }

            return value;
        }

        public void Dispose()
        {
            if (!disposing)
            {
                return;
            }

            _configItems.Clear();
            _configItems = null;
            _configFile = "";
        }
    }
}


texts:
I've made some CAPTCHA reader and maker in Python using Tkinter. Do you know if it's possible to keep image and output files in "memory" not writing them on disc? Because right now everything is 'stiffly' made. And what would you do differently?

gui.py

import tkinter as tk
from PIL import Image, ImageTk
import captcha_maker as captcha
import captcha_reader as cap

class MainApplication(tk.Frame):
    """Main window"""
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.create_widgets()

    def create_widgets(self):
        """Creating widgets"""
        self.input_label = tk.Label(self, text="Text: ")

        self.input_text = tk.Entry(self)

        self.input_button = tk.Button(self, text="Generate captcha",
                                        command=self.make_captcha)
        self.img = ImageTk.PhotoImage(Image.open('bin/blank'))
        self.image_label = tk.Label(self, image= self.img)
        self.image_label.image = self.img

        self.strings = tk.StringVar()
        self.read_button = tk.Button(self, text="Read captcha",
                                        command=self.read_captcha)
        self.output_text = tk.Label(self, textvariable=self.strings)

        self.input_label.grid(row=0, column=0)
        self.input_text.grid(row=0, column=1)
        self.input_button.grid(row=1, column=0)
        self.image_label.grid(row=1, column=1)
        self.read_button.grid(row=2, column=0)
        self.output_text.grid(row=2, column=1)

    def make_captcha(self):
        captcha.make(self.input_text.get())
        self.img2 = ImageTk.PhotoImage(Image.open('bin/result'))
        self.image_label.configure(image=self.img2)
        self.image_label.image = self.img

    def read_captcha(self):
        cap.read()
        with open('bin/output.txt', 'r') as f:
            read_data = f.read().rstrip()
        self.strings.set(read_data)

if __name__ == "__main__":
    root = tk.Tk()
    MainApplication(root).grid()
    root.mainloop()

captcha_maker.py

from PIL import Image, ImageDraw, ImageFont, ImageTk
import io

def make(text):
    """Making simple and regular captcha"""
    im = Image.new("RGB", (len(text) * 13 , 27), "white")
    im.save('bin/blank', "png")
    base = Image.open('bin/blank').convert('RGBA')
    txt = Image.new('RGBA', base.size, (255,255,255,0))
    fnt = ImageFont.truetype('bin/Ubuntu-B.ttf', 24)
    d = ImageDraw.Draw(txt)
    d.text((0,0), text, font=fnt, fill=(0,0,0,255))
    out = Image.alpha_composite(base, txt)
    out.save("bin/result", "png")

if __name__ == ("__main__"):
    make("one")

captcha_reader.py

import subprocess
def read():
    """Just calling tesseract command from python"""
    subprocess.call(["tesseract", "bin/result", "bin/output"])

if __name__ == "__main__":
    read()


texts:
This is the problem:

  You are given  queries. Each query is of the form two integers
  described below:
  - 1: Insert x in your data structure.
  - 2: Delete one occurrence of y from your data structure, if present.
  - 3: Check if any integer is present whose frequency is exactly. If yes, print 1 else 0.

  The queries are given in the form of a 2-D array query of size q where
  queries[i][0] contains the operation, and queriesi contains the
  data element contains the operation and contains the data element. For
  example, you are given array.
  [[1,1],[2,2],[3,2],[1,1],[1,1],[2,1],[3,2]] The output=[0,1]

The question can be found here;
https://www.hackerrank.com/challenges/frequency-queries/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps

My code does not work some of the cases on hackerrank for some reason but I can't figure out why. It is not caused by timeout or compiler error. It gives a 'wrong answer' in the compiler but when I try to test my code with the same input on VSCode, it actually works. It's the first time I am encountering something like this. If I would be more specific, I tested my code manually against this input

  [1, 3],   [1, 38],   [2, 1],   [1, 16],   [2, 1],   [2, 2],   [1, 64],
  [1, 84],   [3, 1],   [1, 100],   [1, 10],   [2, 2],   [2, 1],   [1,
  67],   [2, 2],   [3, 1],   [1, 99],   [1, 32],   [1, 58],   [3, 2]

and it returns [1,1,0] on vs code when I try it. However, on hackerrank it says the wrong answer even though it expects the same result. Any idea what's going on?

Here is my code in javascript;

function freqQuery(queries) {
  let store = [];
  let output = [];
  let obj = {};
  let checkFreq = false;

  for (let i = 0; i < queries.length; i++) {
    let query = queries[i];

    if (query[0] === 1) {
      store.push(query[1]);
    } else if (query[0] === 2) {
      let index = store.indexOf(query[1]);
      if (index > -1) {
        store.splice(index, 1);
      }
    } else {
      let freq = query[1];
      if (store.length === 0) {
        output.push(0);
      } else {
        obj = charToObj(store);
        for (let number in obj) {
          if (obj[number] === freq) {
            checkFreq = true;
            break;
          } else {
            checkFreq = false;
          }
        }
        if (checkFreq) {
          output.push(1);
        } else {
          output.push(0);
        }
      }
    }
  }

  return output;
}

function charToObj(arr) {
  let obj = {};
  for (let i = 0; i < arr.length; i++) {
    if (obj[arr[i]]) {
      obj[arr[i]] += 1;
    } else {
      obj[arr[i]] = 1;
    }
  }
  return obj;
}


texts: Quicker way to go through 550 variables with very similar code

texts:
I'm hoping to figure out a faster way to write this before I resign myself to copying and pasting 500 times.  I have code here that needs to do tons of vlookup matches.  The only thing that changes are two variables each time.

First part is just establishing variables and a count of the rows I need to loop through for each thing:

Sub GetInfo()
    Dim v As Long, vWSs As Variant, Mrange As Range, Vrange As Range
    Dim wsMaster As Worksheet: Set wsMaster = Workbooks("LBImportMacroTemplate.xlsm").Worksheets("MasterTab")
    Dim mf_iA_TEXT As String: mf_iA_TEXT = "iA"
    Dim mf_pLN_TEXT As String: mf_pLN_TEXT = "pLN"
    'ET CETERA, MANY MORE STRING VARIABLES LIKE THIS
    vWSs = Array("B", "E", "L", "I", "T")
    With Workbooks("LBImportMacroTemplate.xlsm")
        Set Mrange = Nothing: Set Vrange = Nothing
'
With ActiveSheet
    lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
    MsgBox lastrow
End With

Now, the main code:

'iA
For v = LBound(vWSs) To UBound(vWSs)
    If CBool(Application.CountIf(.Sheets(vWSs(v)).Range("A2:ZA2"), mf_iA_TEXT)) Then
        Set Mrange = .Sheets(vWSs(v)).Range("A2:ZA2")
        Set Vrange = .Sheets(vWSs(v)).Range("A:ZA")
        mf_iA = Application.Match(mf_iA_TEXT, Mrange, 0)
    For i = 2 To lastrow
            wsMaster.Cells(i, 2) = Application.VLookup(wsMaster.Cells(i, 1), Vrange, mf_iA, 0)
    Next i
        Exit For
    End If
Next v

Then this part repeats again, with two different variables (the mf_x and mf_x_TEXT are the constant naming things but something else will be in place of the x every time.

'pLN
For v = LBound(vWSs) To UBound(vWSs)
    If CBool(Application.CountIf(.Sheets(vWSs(v)).Range("A2:ZA2"), mf_pLN_TEXT)) Then
        Set Mrange = .Sheets(vWSs(v)).Range("A2:ZA2")
        Set Vrange = .Sheets(vWSs(v)).Range("A:ZA")
        mf_pLN = Application.Match(mf_pLN_TEXT, Mrange, 0)
    For i = 2 To lastrow
            wsMaster.Cells(i, 3) = Application.VLookup(wsMaster.Cells(i, 1), Vrange, mf_pLN, 0)
    Next i
        Exit For
    End If
Next v

And repeats and repeats...500+ times.  Is there a better way to do this?  Please teach me if so.

EDIT:  Here's a better explanation of the function, it's in a spreadsheet so .  The MasterTab looks like this

sLN iA  pLN iC  iB  aLN
100
101
102
103
104
105
106
107
108
109
110

those are the headings.  Matching heading can be found on five other tabs:  B, E, L, I, and T.

The code above does a vlookup match to search all 5 tabs for a column with the right name (as defined by the mf_x_TEXT variable).  Then the spreadsheet looks like this:

sLN iA  pLN iC  iB  aLN
100 4444    a   etc etc etc
101 4444    b
102 4746    c
103 8844    d
104 8383    e
105 3456    f
106 8836    g
107 2342    h
108 8888    i
109 1111    j
110 1123    k

like I said, it works, but there are 500 more columns where that came from and I'm just trying to shorten my work so I don't have to copy/paste/click so much.  Hope that helps, let me know if I can provide anything else.


texts: Creating a description of an item from an inventory

texts:
I'm really new to Python (like only a month of study) and I was testing out dictionaries, so I tried to make an 'inventory' where you can pick an item from your inventory and examine it. But I can tell that I'm not doing this in the most efficient or elegant way.

Originally I thought I could make each item its separate dictionary, kind of like this:

#define what's in your inventory using a list
inventory = ["apple", "tire"]

#create a list of items with attributes using dictionaries
apple = {
    "name":"apple",
    "type":"fruit",
    "edible":"edible",
    "color":"red",
}

tire = {
    "name":"tire",
    "type":"object",
    "edible":"not edible",
    "color":"grey"
}

#explain the program to the user
print("Choose an item to examine. Items in your inventory are:")
print(*inventory, sep = ", ")

#set the loop to true
itemsloop = True

#begin the loop
while itemsloop == True:
    #ask for user input
    x = input()

But then I got stuck at the part where it's time to take the input and match it to the name of a dictionary, because one is a string and one isn't. The following code is working, but feels... inelegant and unnecessary to type out (prefix)-name, (prefix)-type, (prefix)-edible for every entry. I feel like there must be a simpler way to accomplish this that I'm just not seeing because I don't think like a programmer yet. I don't know.

If you can explain any more efficient methods with simple terminology (again, huge newbie not just to Python but programming in general), I'd really appreciate it!

#define what's in your inventory using a list
inventory = ["apple", "tire"]

#create a list of items with attributes using a dictionary
items = {
    "apple-name":"apple",
    "apple-type":"fruit",
    "apple-edible":"edible",
    "apple-color":"red",

    "tire-name":"tire",
    "tire-type":"object",
    "tire-edible":"not edible",
    "tire-color":"grey"
}

#explain the program to the user
print("Choose an item to examine. Items in your inventory are:")
print(*inventory, sep = ", ")

#set the loop to true
itemsloop = True

#begin the loop
while itemsloop == True:
    #ask for user input
    x = input()

    if x in inventory:
        #if the input matches something you have, find the attributes of
        #the item in the inventory and print them.
        print("This is a " + items[x + "-color"] + " " +
        items[x + "-name"] + ", a type of " + items[x + "-type"]
        + ". It is " + items[x + "-edible"] + ".")
    elif x == "quit":
        #if the player wishes to quit, end the program.
        itemsloop == False
        break
    else:
        #if the item is not recognized, let the player know.
        print("You don't have that in your inventory.")

(The sample output would be something like, "This is a red apple, a type of fruit. It is edible.")


texts:
My code is designed to simply trigger alarms; it is not supposed to be used by anyone but me.

import subprocess,time,threading, winsound, sys, basepipe
commands = ''
def alarm_checker(alarms):
    """This will be the main threaded process, and will be the meat of the program."""
    global commands
    hours = [int(a.split(":")[0]) for a in alarms]
    mins = [int(a.split(":")[1]) for a in alarms]
    while True:
        localtime = time.localtime()
        for hour,minute in zip(hours,mins):
            if localtime.tm_hour == hour and localtime.tm_min == minute:
                guiserver,guiclient = basepipe.create_double()
                process = subprocess.Popen(r"c:\python34\pythonw.exe c:\python34\guibutton.py",stdout=guiclient)
                while guiserver.read() == '':
                    winsound.Beep(1000,2000)
                hours.remove(hour)
                mins.remove(minute)
        if commands != '':
            for y in commands.split("
"):
                try:
                    exec(y)
                except BaseException as e:
                    sys.stderr.write(str(e))
            commands = ''
        time.sleep(2)
if __name__ == "__main__":
    today = time.localtime().tm_wday
    everyday = ['6:55','7:15','8:12']
    advising = ['13:25','13:55']
    tuethur = ['10:55']
    monday = everyday + advising + ['15:00']
    tuesday = everyday + tuethur
    wednesday = everyday + ['3:50']
    thursday = everyday + advising + tuethur
    friday = everyday
    week = [monday,tuesday,wednesday,thursday,friday,['25:00'],['25:00']]
    thread = threading.Thread(target=alarm_checker,args=(week[today],))
    thread.start()

The basepipe program is a wrapper around windows named pipes in Python. All it does is attempt to implement them in the same way as any other type of IO. One of the peculiarities of windows named pipes is that client read operations are always blocking, while server read operations always raise an error when there is no data in the buffer. I changed this error to simply return ''. create_double() creates a pair of server/client objects. The guibutton.py program does nothing other than open a tcl/tk window. Winsound provides direct access to the sound card, and 1000,2000 means 1000 hertz for 2 seconds, which is annoying as hell.


texts:
I'm learning Rust.

I find it sometimes confusing when compared to other programming languages, especially when dealing with strings and slices.

Her's an implementation of the 99 beer song that I've written, but the code feels clunky and I think it's bad.

How would you have written it, if it was a production code of a real-world software? Any way to improve performance, readability and a more reasonable way to deal with strings in Rust?

const BOTTLE: &str = "bottle";
const S: &str = "s";
const OF_BEER: &str = "of beer";
const N_UP: &str = "N";
const N_DOWN: &str = "n";
const O_MORE: &str = "o more";
const ON_THE_WALL: &str = "on the wall";
const SPACE: &str = " ";
const COMMA: &str = ",";
const PERIOD: &str = ".";
const NL: &str = "\n";
const TAKE: &str = "Take";
const IT: &str = "it";
const ONE: &str = "one";
const DOWN_AND_PASS: &str = "down and pass it around";
const GO_STORE: &str = "Go to the store and buy some more";
const NINE_NINE: &str = "99";

pub fn verse(n: i32) -> String {
    let mut phrase: String;
    let bottles = &format!("{}{}", BOTTLE, S)[..];
    let bottles_of_beer = &format!(
        "{}{}{}",if n == 1 { BOTTLE } else { bottles }, SPACE, OF_BEER
    );
    let n_str = &format!("{}", n)[..];

    if n < 1 {
        phrase = format!("{}{}{}{}", N_UP, O_MORE, SPACE, bottles_of_beer);
    } else {
        phrase = format!("{}{}{}", n_str, SPACE, bottles_of_beer);
    }

    phrase = phrase + SPACE + ON_THE_WALL + COMMA + SPACE;

    if n < 1 {
        phrase = phrase + N_DOWN + O_MORE;
    } else {
        phrase = phrase + n_str;
    }

    phrase = phrase + SPACE + bottles_of_beer + PERIOD + NL;

    if n < 1 {
        phrase = phrase + GO_STORE;
    } else {
        phrase = phrase + TAKE + SPACE + if n == 1 { IT } else { ONE } + SPACE + DOWN_AND_PASS
    }

    phrase = phrase + COMMA + SPACE;

    if n < 1 {
        phrase = phrase + NINE_NINE + SPACE + bottles;
    } else {
        let n = n - 1;

        if n < 1 {
            phrase = phrase + N_DOWN + O_MORE + SPACE + bottles;
        } else {
            phrase = phrase + &format!("{}", n)[..] + SPACE + if n == 1 { BOTTLE } else { bottles };
        }
    }

    phrase = phrase + SPACE + OF_BEER + SPACE + ON_THE_WALL + PERIOD + NL;

    return phrase;
}

pub fn sing(start: i32, end: i32) -> String {
    let mut s = String::new();
    let mut x = start;

    while x >= end {
        if x < start {
            s = s + NL;
        }
        s = s + &verse(x)[..];
        x -= 1;
    }

    return s
}


texts:
Please consider evaluating the code below for best practices, efficiency, and mistakes. I got some of the code from W3 schools (I know, I know, but they've come a long way) and assimilated it to what I need. Particularly, the days = hours = minutes = seconds = 0; is likely going to cause people stress but after research and evaluation, I found that it works well in this case.
Please evaluate my JS code. Thank you. CODEPEN
IMPRORTANT: The code below checks for the existence of an ACF variable (exposed via the functions.php with a WordPress backend), upon which this entire code is based. I replaced the variable with an example string which would be returned by this field.
(function () {
    let acf_vars = {timer: "2021 1 21 13 08 00"}; // this code is a replacement for the ACF variable

    if (!acf_vars.timer) {
        return document
            .querySelectorAll('.mobile-ticker')
            .forEach((container) => (container.style.display = 'none'));
    }

    const backendTimer = acf_vars.timer.split(' ');
    const y = backendTimer[0];
    const M = +backendTimer[1] - 1; // monthIndex in Date Object begins with 0, so we subtract 1
    const d = backendTimer[2];
    const h = backendTimer[3];
    const m = backendTimer[4];
    const s = backendTimer[5];

    // new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])
    const countDownDate = new Date(y, M, d, h, m, s, 0).getTime();

    const timerInterval = setInterval(() => {
        const now = new Date().getTime();
        const distance = countDownDate - now;
        const expiredTimer = distance <= 0;

        let days = Math.floor(distance / (1000 * 60 * 60 * 24));
        let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        let seconds = Math.floor((distance % (1000 * 60)) / 1000);

        if (expiredTimer) {
            days = hours = minutes = seconds = 0;
            clearInterval(timerInterval);
        }

        if (typeof window.innerWidth === 'number' && window.innerWidth < 768) {
            document.querySelector('.ticker-mobile #days').innerHTML = days;
            document.querySelector('.ticker-mobile #hours').innerHTML = hours;
            document.querySelector('.ticker-mobile #minutes').innerHTML = minutes;
            document.querySelector('.ticker-mobile #seconds').innerHTML = seconds;
        } else {
            document.querySelector('.ticker-desktop #days').innerHTML = days;
            document.querySelector('.ticker-desktop #hours').innerHTML = hours;
            document.querySelector('.ticker-desktop #minutes').innerHTML = minutes;
            document.querySelector('.ticker-desktop #seconds').innerHTML = seconds;
        }
    }, 1000);
})();


texts:
I'm trying to write a simple 'n' layered ANN in haskell for supervised learning, it will eventually have back prop and you'll be able to use it in a step by step fashion through a GUI which will graph the error function. This is for learning (so I'm not looking for suggestions on libraries that already solve this problem). In this review I'm mainly looking for feedback on how I've arranged my code and if there are better ways to represent a neural network in Haskell.

The approach I'm trying to take is to separate the forward pass from the backward pass, so that the training can be controlled by the consumer (rather than having a network that is just a one shot IO which does forward -> back recursively until error < x). The reason for this is that I can then separate the rendering of the networks state at any given pass (i.e. after each forward pass I can easily just render the current loss of the whole network by applying the cost function across the output vector).

Here is the current code for a forward pass of the network. It takes a list of double (which is the input vector) and a list of matrix of double (where each element in the list is a weight matrix representing the weights of each connection on a given layer in the network). The activation function then creates an output vector by recursively applying a forwardPass function through each layer until the final layer 'n' has been evaluated.

Here is the code for that:

module Training (randomWeights, activate, cost) where

  import Data.Matrix
  import System.Random

  activate :: [Double] -> [Matrix Double] -> Matrix Double
  activate i weights = forwardPass inputs weights where
    inputSize = length i
    inputs = fromList 1 inputSize i
    forwardPass inputs weights
      | length weights == 1 = squashedOutputs
      | otherwise = forwardPass (squashedOutputs) (tail weights)
      where
        squashedOutputs = mapPos (\(row, col) a -> leakyRelu a) layerOutputs where
          layerOutputs = multStd2 inputs (head weights)
          leakyRelu a
            | a > 0.0 = a
            | otherwise = 0.01 * a

  randomWeights :: (RandomGen g) => g -> Int -> Int -> Matrix Double
  randomWeights generator inputSize outputSize = weights where
    weights = matrix inputSize outputSize (\(col, row) -> (take 10000 $ randomRs (-1.0, 1.0) generator)!!(col * row))

The randomWeights function is consumed in the main function of my program and is used to generate the list of matrix of double to be passed to the forwardPass (i.e. each layers weights).

The main function looks like this:

  main :: IO()
  main = do
    generator <- newStdGen

    let expected = 0.0
    let inputs = [0, 1]

    let inputWeights = randomWeights generator (length inputs) 3
    let hiddenWeights = randomWeights generator 3 1
    let outputWeights = randomWeights generator 1 1

    let outputs = activate inputs [inputWeights, hiddenWeights, outputWeights]

    print inputs
    print outputs

So it a bit like a unit test (eventually I will wrap the activate/backprop loop into a structure that a user can control by a 'next' button on a GUI, but for now I simply want a solid forwardPass foundation to build off.

Does all of this look like reasonable haskell, or are there some obvious improvements I can make?


texts: Looping through rows of data sets in files

texts:
I have files containing data sets which contain 11,000 rows. I have to run a loop through each row, which is taking me 25 minutes for each file.

     z <- read.zoo("Title.txt", tz = "")
  for(i in seq_along(z[,1])) {
    if(is.na(coredata(z[i,1]))) next
   ctr <- i
    while(ctr < length(z[,1])) {
     if(       (   abs  ( coredata(z[i,1]) -coredata(z[ctr+1,1])  )      )  > std_d) {
       z[ctr+1,1] <- NA
       ctr <- ctr + 1

      } else {
  break
    }
 }
}

Where Title.txt is a file containing 11,000 rows. It looks like this (first five rows):

"timestamp" "mesured_distance" "IFC_Code" "from_sensor_to_river_bottom"
 "1" "2012-06-03 12:30:07-05" 3188 1005 3500
 "2" "2012-06-03 12:15:16-05" 3189 1005 3500
 "3" "2012-06-03 12:00:08-05" 3185 1005 3500
 "4" "2012-06-03 11:45:11-05" 3191 1005 3500
 "5" "2012-06-03 11:30:15-05" 3188 1005 3500

How can I increase the speed of this code?


texts:
Write a program by creating an array of 9 integers that represent the
  positions in the tic-tac-toe board. Once the array is created, assign
  values to the board and print the contents of the board out. The
  values for the board are:

  Board Value: X, Integer in Array: 10
  Board Value: O, Integer in Array: 100
  Board Value: Empty, Integer in Array: 0

  This is an example of an array that represents a board:

[10|0|0|100|0|10|10|100|0]

  Here is what the above array would look like when printed to the screen:

+---+---+---+
| X |   |   |
+---+---+---+
| O |   | X |
+---+---+---+
| X | O |   |
+---+---+---+

And I basically solved the problem:

public class problem5 {

    public static void main(String[] args) {

        int[] a = new int[9];
        a[0] = a[5] = a[6] = 10;
        a[3] = a[7] = 100;
        a[1] = a[2] = a[4] = a[8] = 0;
        String[] b = new String[9];
        int x = 0;

        while (x < a.length) {
            if (a[x] == 10)
                b[x] = "X";
            else if (a[x] == 100)
                b[x] = "O";
            else if (a[x] == 0)
                b[x] = " ";
            x++;
        }

        System.out.println("+---+---+---+");
        System.out.println("| " + b[0] + " | " + b[1] + " | " + b[2] + " |");
        System.out.println("+---+---+---+");
        System.out.println("| " + b[3] + " | " + b[4] + " | " + b[5] + " |");
        System.out.println("+---+---+---+");
        System.out.println("| " + b[6] + " | " + b[7] + " | " + b[8] + " |");
        System.out.println("+---+---+---+");

    }
}

But  out of curiosity and just for educational purposes, I was wondering if there was a more advanced/shorter way of solving this problem? And by shorter I meant writing a smaller code.


texts:
I need to create thread-safety on a Web-API method, but only when two requests containing the same property value are ran simultaneously.

I have created a mix of WaitHandles and a ConcurrentDictionary to only hold the threads that have another thread processing a similar item.

Is this code thread-safe? The one that worries me is the ContainsKey with the TryAdd.

private readonly static ConcurrentDictionary _processingGateways = new ConcurrentDictionary();

public Models.Profile GetProfile([FromBody] GetProfileRequest request)
{
    if (!ModelState.IsValid)
        throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, new HttpError(ModelState, true)));

    if (_processingGateways.ContainsKey(request.GatewayId))
        _processingGateways[request.GatewayId].WaitOne();
    _processingGateways.TryAdd(request.GatewayId, new AutoResetEvent(false));

    // Wait for this until prev with same gatewayId has finished
    var device = _clientRegistrar.RegisterMobileEndpoint(Mapper.Map(request));

    AutoResetEvent currentHandle;
    _processingGateways.TryRemove(request.GatewayId, out currentHandle);
    currentHandle.Set();

    return Mapper.Map(device);
}


texts: customSignupForm code to allow signup for only the invited user

texts:
I am developing a feature where the user has to request for invitation if he/she wants to sign up on the site. When the request is accepted by the admin, the user gets to sign up, otherwise it shows them an error saying they are not invited at this time, and saves a email so we can follow up with him/her. To be generic, I used the condition INVITE_MODE = True in settings, so if we disable the invitation feature using INVITE_MODE=False, all the users should get to sign up.

Here is my signup form and I am using Django allauth for that:

class CustomSignupForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(CustomSignupForm, self).__init__(*args, **kwargs)

    def clean(self):
        email = self.cleaned_data.get('email')
        print ('email', email)
        email = get_adapter().clean_email(email)
        # if email and app_settings.UNIQUE_EMAIL:
        #     email = self.validate_unique_email(email)
        if email and settings.INVITE_MODE:
            try:
                Invitation.objects.get(email=email, request_approved=True)
            except Invitation.DoesNotExist:
                invitation, created = Invitation.objects.get_or_create(email=email)
                self.add_error('email', 'Sorry at this time you are not invited. But we have added you to our invite list')
        elif email is None:
            self.add_error('email', 'Email field cannot be empty')
        else:
            return email

    def signup(self, request, user):
        # email = self.cleaned_data.get('email')
        # user.email = email
        user.save()

Can anyone suggest a to do this in a better/efficient way?


texts:
I've made a card flip with CSS keyframes but instead of flipping clockwise and then flip counterclockwise to it's original position, I've two separate keyframes that will cause it to rotate in the same direction each time I rotate.

I have jQuery checking if either class exists and adding the first one if neither exists and then I toggle the classes to keep this effect going indefinitely.

Is there a better way of writing this CSS to condense this into one class and have JavaScript just toggle that one class instead of two? If not, is there a better approach to handling the JavaScript?

$(".click").click(function () {
    $flipper = $(".flipper");

    if (!$flipper.hasClass("flipped") && !$flipper.hasClass("second-flip")) {
        $flipper.addClass("flipped");
    } else {
        $flipper.toggleClass("flipped");
        $flipper.toggleClass("second-flip");
    }
});
.flip-container {
    height: 150px;
    width: 150px;

    perspective: 600;
    position: relative;
}
.flipper {
    height: 100%;
    width: 100%;

    position: absolute;
    transform-style: preserve-3d;
    transition: transform 1s;
}
.back, .front {
    height: 100%;
    width: 100%;

    display: block;
    position: absolute;
    backface-visibility: hidden;
}
.front {
    background-color: red;
}
.back {
    background-color: blue;
    transform: rotateY(180deg);
}
.flipped {
    animation: spin180 1s 1 forwards;
}
.second-flip {
    animation: spin360 1s 1 forwards;
}

@keyframes spin180 {
    0% { transform: rotateY(0deg); }
    100% { transform: rotateY(180deg); }
}

@keyframes spin360 {
    0% { transform: rotateY(180deg); }
    100% { transform: rotateY(360deg); }
}

Front

Back

<button class="click">Click me</button>


texts: Create an array which contains specific values of a specific nested object inside an array

texts:
So I have this array of objects, which respectively contain other objects:

const template_columns = [
  {
    "id": 38,
    "name": "Ideas",
    "position": 0,
    "template_id": 4,
    "column_type": "Column",
    "workflow": [
      {
        "action": "Next",
        "move_to": "Backlog",
        "assign_to": "none"
      },
      {
        "action": "Prev",
        "move_to": "First column",
        "assign_to": "none"
      }
    ],
    "_t": "template_column"
  },
  {
    "id": 39,
    "name": "Backlog",
    "position": 1,
    "template_id": 4,
    "column_type": "Column",
    "workflow": [
      {
        "action": "Start",
        "move_to": "Current",
        "assign_to": "none"
      }
    ],
    "_t": "template_column"
  },
  {
    "id": 40,
    "name": "Current",
    "position": 2,
    "template_id": 4,
    "column_type": "Column",
    "workflow": [
      {
        "action": "Review",
        "move_to": "Review",
        "assign_to": "none"
      }
    ],
    "_t": "template_column"
  },
  {
    "id": 41,
    "name": "Review",
    "position": 3,
    "template_id": 4,
    "column_type": "Column",
    "workflow": [
      {
        "action": "Approve",
        "move_to": "Approved",
        "assign_to": "none"
      }
    ],
    "_t": "template_column"
  },
  {
    "id": 42,
    "name": "Approved",
    "position": 4,
    "template_id": 4,
    "column_type": "Columns::Done",
    "workflow": [],
    "_t": "template_column"
  }
]

I need to process this array and return an array with all workflow.action values. I have loadash available and I'm also transpiling the es6 code with babel.

I managed to do so, but I'm wondering if there's a more elegant way to do it:

My solution:

const workflow = _.map (
  _.flatten(
    _.map(template_columns, function(col) {
      return col.workflow
    })
  ), 'action'
)

So is there a better way to achieve what I'm looking for?


texts:
Disclaimer: This is my first post here, so I'm not completely sure if this is on-topic.

I recently added a decorator that wraps a context manager in pyfakefs (I'm a contributor), which has some optional arguments. In order to make the usage more convenient, I allowed both the usage with and without parentheses (mostly arguments are not needed, so the call without parentheses is the default). The code works but is not nice, and also probably not good if performance matters. I will show the full code here, and the question is just - can this be written nicer, and without the need to call another decorator function in the default case.

This is the complete code including comments:

def _patchfs(f):
    """Internally used to be able to use patchfs without parentheses."""

    @functools.wraps(f)
    def decorated(*args, **kwargs):
        with Patcher() as p:
            kwargs['fs'] = p.fs
            return f(*args, **kwargs)

    return decorated

def patchfs(additional_skip_names=None,
            modules_to_reload=None,
            modules_to_patch=None,
            allow_root_user=True):
    """Convenience decorator to use patcher with additional parameters in a
    test function.

    Usage::

        @patchfs
        test_my_function(fs):
            fs.create_file('foo')

        @patchfs(allow_root_user=False)
        test_with_patcher_args(fs):
            os.makedirs('foo/bar')
    """

    def wrap_patchfs(f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            with Patcher(
                    additional_skip_names=additional_skip_names,
                    modules_to_reload=modules_to_reload,
                    modules_to_patch=modules_to_patch,
                    allow_root_user=allow_root_user) as p:
                kwargs['fs'] = p.fs
                return f(*args, **kwargs)

        return wrapped

    # workaround to be able to use the decorator without using calling syntax
    # (the default usage without parameters)
    # if using the decorator without parentheses, the first argument here
    # will be the wrapped function, so we pass it to the decorator function
    # that doesn't use arguments
    if inspect.isfunction(additional_skip_names):
        return _patchfs(additional_skip_names)

    return wrap_patchfs

Some more usage context:
The decorator can be used in unittest methods to execute the test in a fake filesystem. The actual work is done by the patcher, which is instantiated by the decorator. The fake filesystem is represented by the argument fs,which is taken from the patcher instance, and can be used for some convenience functions like file creation or copying of files from the real file system.
In most cases, this will work out of the box (the decorator without parentheses can be used), but in some cases additional configuration is needed, which can be done by adding some optional arguments to the decorator, which are passed to the patcher.


texts:
This is my version of a linked list in C. The function mergeSort requires a reference to the first and to the last nodes, as well as the indices of the first and the last node and a comparator.

You need to compile this source code using C99 standard in order to get it working.

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

typedef struct List {
    int val;
    struct List *next;
} List;

List *new(int value)
{
    List *list = malloc(sizeof(List));
    list->next = NULL;
    list->val = value;

    return list;
}

void freeList(List *list)
{
    List *node = list;
    while(node != NULL) {
        List *n = node->next;
        free(node);
        node = n;
    }
}

void print(List *list)
{
    for(List *node = list; node != NULL; node = node->next) {
        printf("%d ", node->val);
    }
    printf("\n");
}

List *merge(List *part1, List *part2, int (*cmp)(const void *, const void *))
{
    List *temp;

    if(cmp(&part1->val, &part2->val) < 0) {
        temp = part1;
        part1 = part1->next;
    }
    else {
        temp = part2;
        part2 = part2->next;
    }

    List *current = temp;

    while(part1 != NULL && part2 != NULL) {
        if(cmp(&part1->val, &part2->val) < 0) {
            current->next = part1;
            part1 = part1->next;
        }
        else {
            current->next = part2;
            part2 = part2->next;
        }
        current = current->next;
    }

    while(part1 != NULL) {
        current->next = part1;
        current = current->next;
        part1 = part1->next;
    }

    while(part2 != NULL) {
        current->next = part2;
        current = current->next;
        part2 = part2->next;
    }

    return temp;
}

List *mergeSort(List *start,
                List *stop,
                int startIndex,
                int stopIndex,
                int (*cmp)(const void *, const void *))
{
    if(start != stop) {
        int mid = (startIndex + stopIndex) / 2;
        int i = startIndex;

        List *midNode = NULL;
        for(List *node = start; node != stop; node = node->next) {
            if(i == mid) {
                midNode = node;
            }
            i++;
        }
        List *midNodeNext = midNode->next;

        List *part1 = mergeSort(start, midNode, startIndex, mid, cmp);
        List *part2 = mergeSort(midNodeNext, stop, mid + 1, stopIndex, cmp);

        return merge(part1, part2, cmp);
    }

    start->next = NULL;
    return start;
}

int cmp(const void *a, const void *b)
{
    return *(int *)a - *(int *)b;
}

List *push(List *list, List *node)
{
    List *last;
    for(List *node = list; node != NULL; node = node->next) {
        if(node->next == NULL) {
            last = node;
        }
    }
    last->next = node;

    return node;
}

int main()
{
    List *list = new(9);

    push(list, new(4));
    push(list, new(3));
    push(list, new(2));
    push(list, new(1));
    List *stop = push(list, new(8));

    list = mergeSort(list, stop, 0, 5, cmp);

    print(list);

    freeList(list);

    return 0;

}