texts: Generalizing the Initialization of Singleton Derived Classes

texts:
I have the following construct for storing and restoring my applications settings to and from XML.

public interface ISettingsProvider : ICustomXmlSerializableObject
{
    void RestoreDefaultSettings(bool force = false);
}

where I use a wrapper for the XmlSerialization to prevent access from multiple threads at the same time. The interface ICustomXmlSerializableObject is merely

public interface ICustomXmlSerializableObject
{
    string GetSerializedFilePath();
}

I then have an abstract class that all my setting providers inherit from, this is

public abstract class SettingsProviderBase : ISettingsProvider
{
    public virtual string Extension { get { return ".settings"; } }

    public abstract string GetSerializedFilePath();

    public abstract void RestoreDefaultSettings(bool force = false);
}

Then an example of a setting provider concrete implementation would be

public class ConsoleSettingsProvider : SettingsProviderBase
{
    private static ConsoleSettingsProvider instance = null;

    private ConsoleSettingsProvider() { }

    public static ConsoleSettingsProvider Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new ConsoleSettingsProvider();
                if (File.Exists(instance.GetSerializedFilePath()))
                {
                    ConsoleSettingsProvider o = instance.Deserialize();
                    instance = o ?? instance;
                }
                instance.RestoreDefaultSettings();
            }
            return instance;
        }
    }

    public override void RestoreDefaultSettings(bool force = false)
    {
        if (InterfaceSettings == null || force)
            InterfaceSettings = new InterfaceSettings();
    }

    public override string GetSerializedFilePath()
    {
        // Build the required storage directory.
        string path = Utils.CheckBuildRoamingAppDataDirectory(Constants.Trademark);
        return Path.Combine(path, "Console" + Extension);
    }

    [XmlElement, Browsable(false)]
    public InterfaceSettings InterfaceSettings { get; set; }
}

[Serializable]
public class InterfaceSettings : ISettings
{
    private Font font;

    public InterfaceSettings()
    {
        Font = new Font("Consolas", 9.0f);
    }

    public Font Font
    {
        get { return font; }
        set { font = value; }
    }
}

Where ISettings is a marker interface that may allow me to do something later.

My question is concerning the refactoring of this class hierarchy. It would be nice to move the instantiation of these ISettingsProvider types into the abstract class and save some code as the instantiation method is the same for each derived class. Perhaps moving the property to a method and changing the SettingProviderBase class to

public abstract class SettingsProviderBase : ISettingsProvider
{
    public static virtual T instance = null;

    public static virtual T Instance<T>() where T : ISettingsProvider
    {
        if (instance == null)
        {
            instance = new T();
            if (File.Exists(instance.GetSerializedFilePath()))
            {
                T o = instance.Deserialize();
                instance = o ?? instance;
            }
            instance.RestoreDefaultSettings();
        }
        return instance;
    }

    public virtual string Extension { get { return ".settings"; } }

    public abstract string GetSerializedFilePath();

    public abstract void RestoreDefaultSettings(bool force = false);
}

But this clearly is not possible. Can I achieve what I want and if so, how?


texts:
Is this a good form validation script?

$(document).ready(function() {

    $("form").submit(function() {

        var shouldSubmit = true;

        $(this).children(":input:not(:button, [type=\"submit\"], [type=\"reset\"])").each(function() {

            if ($(this).val() == "")
            {
                shouldSubmit = false;
                return shouldSubmit;
            }

        });

        if ($("input:checkbox").length > 0)
        {
            if ($("input:checkbox:checked").length == 0)
                shouldSubmit = false;
        }

        if ($("input:radio").length > 0)
        {
            if ($("input:radio:checked").length == 0)
                shouldSubmit = false;
        }

        if (shouldSubmit == false)
            alert("All form fields must be filled out.");

        return shouldSubmit;

    });

});


texts: Dynamic array sorting and storing program

texts:
I have written a program which closely resembles the way contacts are added and dynamically sorted in ascending order in your phone or other device. Though I have used Integers instead of String, I was just wondering if this has any real world use and how I can improve it.

import java.util.*;

public class Ascending
{

    ArrayList<Integer> array = new ArrayList<Integer>();

    public Ascending()
    {
        array.add(2);
        array.add(4);
        array.add(6);
        array.add(8);
    }

    public static void main()
    {
        Ascending obj = new Ascending();
        obj.ascendingOrder();
    }

    public void ascendingOrder()
    {
        for(int loop=0;loop<=10;loop++)
        {
            Scanner sc = new Scanner(System.in);
            System.out.println("The array is 2,4,6,8 ");
            System.out.println("Enter a number you wish to insert in the array");
            int input = sc.nextInt();
            int i,size = array.size(),last=size-1;

            for(i=0;i<size;i++)
            {
                if(input<array.get(i))
                {
                    array.add(i,input);
                    System.out.println("\nSorted array -:");
                    for(int y:array)
                    {
                        System.out.println(y);

                    }
                    break;
                }
            }

            if(input>array.get(last))
                {
                    array.add(size,input);
                    System.out.println("\nSorted array -:");

                    for(int q:array)
                    {
                        System.out.println(q);
                    }
                }
        }
    }
}


texts: How to verify if value already added to the list and if so, then update the value?

texts:
I use 3 lists to store field name, its value and score. If field name is already added to according list, then I just need to update other 2 lists. If it is not there, then I need to add it. I do the following:

user = User.get_by_key_name(user_key_name)
if user:
    field_names = user.field_names
    field_values = user.field_values
    field_scores = user.field_scores
    if field_name in user.field_names:
        # field_names[field_index] = field_name
        field_index = user.field_names.index(field_name)
        field_values[field_index] = field_value
        field_scores[field_index] = field_score
    else:
        field_names.append(field_name)
        field_values.append(field_value)
        field_scores.append(field_score)
    user.field_names = field_names
    user.field_values = field_values
    user.field_scores = field_scores
    user.put()

Is it correct approach?


texts: Code to initialize a .NET object from a CSV file

texts:
I am initializing the following object from a CSV file:

private class MassUploadUser
    {
        public string email { get; set; }

        public string firstName { get; set; }

        public string lastName { get; set; }

        public string role { get; set; }

        public bool active { get { return true; } }
    }

I later serialize this to JSON using Newtonsoft, and then Post this to a RESTful API. TextFieldParser is from Microsoft.VisualBasic.FileIO by the way.

using (var parser = new TextFieldParser(Program.file))
{
    parser.SetDelimiters(",");

    string[] header = parser.ReadFields();

    while (!parser.EndOfData)
    {
            string[] fields = parser.ReadFields();

            var massUploadUser = new MassUploadUser();
            string password = null;

            for (int i = 0; i < fields.Length; i++)
            {
                switch (header[i])
                {
                    case "First Name":
                        massUploadUser.firstName = fields[i];
                        break;

                    case "Last Name":
                        massUploadUser.lastName = fields[i];
                        break;

                    case "Role":
                        massUploadUser.role = fields[i];
                        break;

                    case "email":
                        massUploadUser.email = fields[i];
                        break;

                    case "Password":
                        password = fields[i];
                        break;
                }
            }

           // After the for loop, I have some additional logic
           // to serialize the newly-created object to JSON
           // and then POST it to a RESTful API
           DoPostToWebService(massUploadUser, password);

          // At this point, we created the new user on the server, so no need
          // to keep the current instance of massUploadUser around
        }

Can this be improved? Is there a more "general" way to do this?


texts: Non-repeatability (plagiarism and time travel)

texts:
I heard/read that writers of texts can be recognized by counting their used words and compare these to previous works. As a code kata  I experimented with this a bit and found some disturbing facts.

'Romeo and Juliet' was written by one of the Bronte sisters.
Shakespeare plagiarized it from the future.
My program is not repeatable.

I think the last is most disturbing, see the numbers of corresponding words between brackets in my results below.

Used code is also below and used .txt files were downloaded from https://www.gutenberg.org/ and conveniently renamed, temporary available in a zip at http://kuiken.dyndns.org/spul/books.zip.

Questions:

Why is my code not repeatable
Coding style comments

Results:

jk@ASUS-flaptop:~/PythonFun/Boeken$ python books.py

I read WutheringHeights.txt by Bronte
I read PrideAndPrejudice.txt by Austen
I read TheMerchantOfVenice.txt by Shakespeare

I think SensAndSensibility.txt is written by Austen (405)
I think RomeoAndJuliet.txt is written by Bronte (278)
I think JaneEyre.txt is written by Bronte (376)
I think Hamlet.txt is written by Shakespeare (324)

jk@ASUS-flaptop:~/PythonFun/Boeken$ python books.py

I read WutheringHeights.txt by Bronte
I read PrideAndPrejudice.txt by Austen
I read TheMerchantOfVenice.txt by Shakespeare

I think SensAndSensibility.txt is written by Austen (404)
I think RomeoAndJuliet.txt is written by Bronte (279)
I think JaneEyre.txt is written by Bronte (376)
I think Hamlet.txt is written by Shakespeare (319)

Code:

from collections import Counter
from string import ascii_letters, whitespace

def read_book(filename):
    with open(filename) as f:
        return f.read()

def make_words(text):
    '''removes weird characters and split into words'''
    remain = ascii_letters + whitespace
    filtered = ""
    for ch in text:
        if ch in remain:
            filtered += ch
    return filtered.lower().split()

def most_used(words, n=500):
    '''returns a `set` of the `n` most used words'''
    counting = Counter(words)
    counted = counting.most_common(n)
    return set([item[0] for item in counted])

def read_and_analyse(filename):
    '''reads a book and returns most used words'''
    book = read_book(filename)
    words = make_words(book)
    favorites = most_used(words)
    return favorites

class WriterKnower():

    def __init__(self):
        self.analysed_books = []

    def read_and_remeber_words(self, filename, writer):
        favorite_words = read_and_analyse(filename)
        self.analysed_books.append({ 'favorite_words' : favorite_words,
                                     'writer' : writer})
        print("I read %s by %s" % (filename, writer))

    def read_and_recognize(self, filename):
        favorit_words = read_and_analyse(filename)
        writer = 'unknown'
        max_identical_words = 0
        for book in self.analysed_books:
            common = len(favorit_words.intersection(book['favorite_words']))
            if (common > max_identical_words):
                max_identical_words = common
                writer = book['writer']
        print("I think %s is written by %s (%d)" %
              (filename, writer, max_identical_words))

if __name__ == "__main__":

    nerd = WriterKnower();

    print()
    nerd.read_and_remeber_words('WutheringHeights.txt', 'Bronte')
    nerd.read_and_remeber_words('PrideAndPrejudice.txt', 'Austen')
    nerd.read_and_remeber_words('TheMerchantOfVenice.txt', 'Shakespeare')
    print()
    nerd.read_and_recognize('SensAndSensibility.txt')
    nerd.read_and_recognize('RomeoAndJuliet.txt')
    nerd.read_and_recognize('JaneEyre.txt')
    # to be a bit reinsured....
    nerd.read_and_recognize('Hamlet.txt')
    print()


texts: Converting input from a FileReader to JSON and outputting it again

texts:
Below is my code which I use to read data from a remote URL (which is GZipped), convert it to a Map, process the map (remove various unwanted fields, etc), the write it back to a file in JSON format.

Unfortunately, it's ugly. I'm doing multiple things in the same method, but can't think of a good way to break them apart, as the input files can have hundreds of thousands of lines, so they will cause me to run out of memory quickly if I try to read in the whole thing, then process it, then output it.

Can anyone offer any assistance/suggestions?

private void importTdatFile(String fileURL) {

    String filename = getFilename(fileURL) + ".gz";

    try {
        URL url = new URL(fileURL);

        // set up input
        GZIPInputStream gzis;
        if (new File(filename).isFile()) {
            InputStream is = ClassLoader.getSystemResourceAsStream(fileURL);
            gzis = new GZIPInputStream(is);
            System.out.println("Using tdat header from classes directory");
        } else {
            gzis = new GZIPInputStream(url.openStream());
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(gzis));

        // set up output
        BufferedWriter writer = new BufferedWriter(new FileWriter(catalog.getName() + ".json"));

        // create a template so I only have to create a map once
        Map<String, String> template = new LinkedHashMap<String, String>(catalog.getFieldData().size());
        for (String fieldName : catalog.getFieldData().keySet()) {
            template.put(fieldName, null);
        }

        // start processing
        while (reader.ready()) {
            String line = reader.readLine();
            if (line.matches("^(.*?\\|)*$")) {
                Map<String, String> result = new HashMap<String, String>();
                String[] fieldNames = catalog.getFieldData().keySet().toArray(new String[]{});
                String[] fieldValues = line.split("\\|");

                for (int i = 0; i < fieldValues.length; i++) {
                    FieldData fd = catalog.getFieldData().get(fieldNames[i]);
                    if (catalog.getFieldDataSet().contains(fd)) {
                        result.put(fieldNames[i], fieldValues[i]);
                    }
                }

                result = removeNulls(result);
                result = removeUnwantedFields(result, catalog);
                result = fixFieldPrefixes(result, catalog);
                result = fixFieldNames(result, catalog);

                writer.write(getJsonLine(result));

            }
        }

        writer.close();
        reader.close();
        gzis.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


texts: Check whether a number can be dialed on a phone keypad without diagonal moves

texts:
I'm trying to write/come up with an algorithm for a phone keypad traversal.

Let's say I have a rook on a keypad. The rook can traverse only horizontally and vertically. My code has to input a phone number and check whether the rook is able to dial it (shouldn't go diagonally) and return a boolean based on the result.

Example: A phone number "4632871" is termed as "true" since the rook can traverse without going diagonally whereas "4853267" is termed as "false"

Below is my code implementation:

var data = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

function rookTraversal(arr, phoneNumber) {

  var arrIndex = [],
    numArray = [];

  var number = phoneNumber.split('');

  for (var i = 0; i < arr.length; i++) {
    for (var j = 0; j < arr.length; j++) {
      arrIndex.push([i, j]);
    }
  }

  arrIndex = arrIndex.map((item, index) => ({
    [index + 1]: item,
  }));

  number.forEach((item) => {
    numArray.push(arrIndex[item - 1]);
  });

  let numArrayKeys = numArray.reduce((acc, x) => [...acc, Object.values(x).map((y) => y)], []);

  for (let i = 1; i < numArrayKeys.length; i++) {
    var x1 = numArrayKeys[i - 1][0][0];
    var y1 = numArrayKeys[i - 1][0][1];
    var x2 = numArrayKeys[i][0][0];
    var y2 = numArrayKeys[i][0][1];

    if (x1 !== x2 && y1 !== y2) {
      return false;
    }
  }

  return true;
}

console.log(rookTraversal(data, '4631782'));
console.log(rookTraversal(data, '4853267'));

Is there a way to optimize this piece of code?


texts: Calculate the Fibonacci sequence using bash

texts:
I would like your opinion on my shell script that prints the Fibonacci sequence.

#!/bin/bash

first=0
second=1
third=1
echo -n "Term: "
read term

fub=$((second+third))
echo $second
echo $third
echo $fub

for ((i=1; i<term; i++))
do
  third=$((fub+third))
  echo $third
  fub=$((third+fub))
  echo $fub
done

I tried to calculate the Fibonacci sequence in the simplest way (without the use of recursive functions).


texts:
Given an element of the permutation group, expressed in Cauchy notation, it is often useful to have it expressed in disjoint cycles (for example to apply the permutation to the keys of a dictionary).

The code below provides a possible answer to the problem: how to go from the Cauchy notation to the disjoint cycle and backward?

What I could not answer is: how to make it more efficient? Should this be made recursive?  Why or why not?

E.g.
Cauchy notation

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

means permute 1 with 3, 3 with 2, 2 with 1 and 4 with 6, leaving 5 alone.

Corresponding disjoint cycles are:

c = [[1,3,2], [4,6]]

I proposed the same code here and here.

def is_valid_permutation(in_perm):
    """
    A permutation is a list of 2 lists of same size:
    a = [[1,2,3], [2,3,1]]
    means permute 1 with 2, 2 with 3, 3 with 1.
    :param in_perm: input permutation.
    """
    if not len(in_perm) == 2:
        return False
    if not len(in_perm[0]) == len(in_perm[1]):
        return False
    if not all(isinstance(n, int) for n in in_perm[0]):
        return False
    if not all(isinstance(n, int) for n in in_perm[1]):
        return False
    if not set(in_perm[0]) == set(in_perm[1]):
        return False
    return True

def lift_list(input_list):
    """
    List of nested lists becomes a list with the element exposed in the main list.
    :param input_list: a list of lists.
    :return: eliminates the first nesting levels of lists.
    E.G.
    >> lift_list([1, 2, [1,2,3], [1,2], [4,5, 6], [3,4]])
    [1, 2, 1, 2, 3, 1, 2, 4, 5, 6, 3, 4]
    """
    if input_list == []:
        return []
    else:
        return lift_list(input_list[0]) + (lift_list(input_list[1:]) if len(input_list) > 1 else []) \
            if type(input_list) is list else [input_list]

def decouple_permutation(perm):
    """
    from [[1, 2, 3, 4, 5], [3, 4, 5, 2, 1]]
    to   [[1,3], [2,4], [3,5], [4,2], [5,1]]
    """
    return [a for a in [list(a) for a in zip(perm[0], perm[1]) if perm[0] != perm[1]] if a[0] != a[1]]

def merge_decoupled_permutation(decoupled):
    """
    From [[1,3], [2,4], [3,5], [4,2], [5,1]]
    to   [[1, 3, 5], [2, 4]]
    """
    ans = []
    while len(decoupled):
        index_next = [k[0] for k in decoupled[1:]].index(decoupled[0][-1]) + 1
        decoupled[0].append(decoupled[index_next][1])
        decoupled.pop(index_next)
        if decoupled[0][0] == decoupled[0][-1]:
            ans.append(decoupled[0][:-1])
            decoupled.pop(0)
    return ans

def from_permutation_to_disjoints_cycles(perm):
    """
    from [[1, 2, 3, 4, 5], [3, 4, 5, 2, 1]]
    to   [[1, 3, 5], [2, 4]]
    """
    if not is_valid_permutation(perm):
        raise IOError('Input permutation is not valid')
    return merge_decoupled_permutation(decouple_permutation(perm))

def from_disjoint_cycles_to_permutation(dc):
    """
    from [[1, 3, 5], [2, 4]]
    to   [[1, 2, 3, 4, 5], [3, 4, 5, 2, 1]]
    """
    perm = [0, ] * max(lift_list(dc))
    for cycle in dc:
        for i, c in enumerate(cycle):
            perm[c-1] = cycle[(i + 1) % len(cycle)]
    return [list(range(1, len(perm) + 1)), perm]


texts: Reducing duplicated code when using many Netlogo Link Breeds

texts:
Background

I am using many link breeds in Netlogo. I created various getter/setter and lookup functions for each of these breeds.

Issue

I need to increase my links from 5 different breeds to 44 breeds. And I'm sure copy and pasting these lines of code is not the best approach. If this was a Bash-Shell I would use Indirect Parameter Expansion to reduce the amount of code.

How can I increase the number of link breeds without duplicating so many lines of code?

Code

Declaration

undirected-link-breed [infection-activities infect-activity]
undirected-link-breed [exposure-activities exposure-activity]
undirected-link-breed [watch-activities watch-activity]
undirected-link-breed [mutation-activities mutation-activity]
undirected-link-breed [spillover-activities spillover-activity]
undirected-link-breed [unknown-activities unknown-activity]

Instantiation

infection-activities-own[
  activity-size
  activity-history
]
exposure-activities-own[
  activity-size
  activity-history
]
watch-activities-own[
  activity-size
  activity-history
]
mutation-activities-own[
  activity-size
  activity-history
]
spillover-activities-own[
  activity-size
  activity-history
]
unknown-activities-own[
  activity-size
  activity-history
]

Some Sample Getters Functions

to-report get-activity-from-field-surveillance
  let activity-breed [breed] of one-of links
  report get-activity-breed-common-name activity-breed
end

to-report get-activity-breed-common-name [layer]
  if layer = infection-activities [report "infection" ]
  if layer = exposure-activities [report "exposure" ]
  if layer = watch-activities [report "watch" ]
  if layer = mutation-activities [report "mutation" ]
  if layer = spillover-activities [report "spillover" ]
end

to-report get-activity [layer]
  set num-edges num-edges + 1
  if layer = "infection" [report infection-activities ]
  if layer = "exposure" [report exposure-activities ]
  if layer = "watch" [report watch-activities ]
  if layer = "mutation" [report mutation-activities ]
  if layer = "spillover" [report spillover-activities ]
  report "ACTIVITY not found"
end

to-report get-activity-breed-for-link [layer selected-agent selected-vector]
  let vector-who get-vector-who selected-vector
  let agent-who get-agent-who selected-agent
  set num-edges num-edges + 1
  if layer = "infection" [report infect-activity vector-who agent-who]
  if layer = "exposure" [report exposure-activity vector-who agent-who]
  if layer = "watch" [report watch-activity vector-who agent-who]
  if layer = "mutation" [report mutation-activity vector-who agent-who]
  if layer = "spillover" [report spillover-activity vector-who agent-who]
  report "ACTIVITY not found"
end

to-report get-activity-color [layer]
  if layer = "infection" [report blue ]
  if layer = "exposure" [report 113 ]
  if layer = "watch" [report brown ]
  if layer = "mutation" [report yellow ]
  if layer = "spillover" [report green ]
  report "ACTIVITY not found"
end


texts: Rearrange page numbers for printing a book

texts:
I didn't want my title to be too long so to clear up any confusion I'll explain better here what my code does.

It asks for the total pages of a book(PDF file in my case), and returns the page numbers in a specific order. The groups of 32 pages will each make a booklet that when all booklets are stapled together and laid one on top of the other will be a book ready for binding.

One issue with how I wrote the program is if "pages" is not a multiple of 4, then there will be extraneous pages at the end of the list (i couldn't think of a way to pop those). Another tid-bit, print_order doesn't need to be a list, it just needs to be page numbers separated by commas and I knew list items were separated by commas so having a list of ints would give me what I needed. The formula for printing a book on a single sided printer goes like this (n, f, f+1, n-1) where n is the last page, and f is the first page of each booklet/the whole book. The reason a long book needs to be broken into booklets is because if I take a stack of 100 papers and just fold the whole stack in half the spine would be too wide and the middle pages would be poking out of the cover. So using n and f as the first and last page, respectively, of smaller booklets allows me to print a whole book into something more practical.

I'm not worried about PEP formatting on this one I'm really just curious how this could be written more efficiently. I know python is extremely powerful and I'm not taking full advantage of what it has to offer. This is how I managed to organize my thoughts into doing what I required. I know that there are many out there who could do this in a much simpler way, and I just want to look those ways over so that I can improve my coding style!

pages = float(input("How many total pages is the book?" ))
num_booklets = pages/32
if (pages < 32):
    num_booklets = 1
pages_per_booklet = int(pages/num_booklets)
last_booklet = int(pages%32)

f = 1               #first page of the book
n = int(pages_per_booklet)  #last page of the first booklet
k = 1               #number of booklets completed
print_order = []

while (len(print_order) < pages):
    while ((len(print_order) < pages_per_booklet*k)
    and (len(print_order) < pages)):
        print_order.extend([n, f, f+1, n-1])
        n -= 2
        f += 2
    k += 1
    n = pages_per_booklet * k
    f = 1 + (pages_per_booklet*(k-1))
    if ((len(print_order)+pages_per_booklet) > pages):
        n = int(pages)
        f = int(pages) - last_booklet

print(print_order)


texts: Class / Superclass / Specific class matching condition, can it be simpler?

texts:
I recently built a way to automagically dismiss firstResponders for an app I'm building. Is there a more efficient way to approach this?

- (void)resignFieldStackRespondersExcept:(id)fieldException
{
    for (id field in self.fieldStack) {
        if ([field isKindOfClass:[fieldException class]] ||
            ([[field class] isSubclassOfClass:[fieldException class]] || [[fieldException class] isSubclassOfClass:[field class]]) ||
            (([[field class] isSubclassOfClass:[UITextField class]] && [[fieldException class] isSubclassOfClass:[UITextView class]]) ||
             ([[field class] isSubclassOfClass:[UITextView class]] && [[fieldException class] isSubclassOfClass:[UITextField class]]))) {
            continue;
        }

        [self resignField:field];
    }
}

- (void)resignField:(id)field
{
    if ([field isKindOfClass:[AccessoryPicker class]]) {
        [field closePicker:YES];
    }

    if ([field isKindOfClass:[TagsTextView class]]) {
        [field saveTrailingTag];
    }

    if ([field isKindOfClass:[UITextField class]] || [field isKindOfClass:[UITextView class]]) {
        [field resignFirstResponder];
    }
}


texts: A VBA Product Dictionary with a Collection of Product Services

texts:
I need to extract unique Product Group names along with its corresponding services from a table in a worksheet. The table is generated by a bot and is not filtered, I have sorted it by alphabetical order. The data is not fixed and can contain anywhere from 5 - 100 rows of data, depending on the month which the report from the bot is generated.
I decided to use a Dictionary to store the the Product Group Name as they Key, while using a Collection to store services. The Collection only stores unique services by using On Error Resume Next
What changes could I make to my code?
Snippet of my Table

Code
Public Sub BuildTMProductDictionary()

Dim tmData As Variant
tmData = Sheet1.ListObjects("Table1").DataBodyRange.Value

Dim i As Long
For i = LBound(tmData, 1) To UBound(tmData, 1)
    Dim product As String
    product = tmData(i, 1)

    'store unique services in a collection, On Error Resume Next used to avoid duplicates
    On Error Resume Next
    Dim services As New Collection
    services.Add (tmData(i, 2)), (tmData(i, 2))

    'get the product name of the next row
    Dim nextProduct As String
    nextProduct = tmData(i + 1, 2)

    'compare the current product against the next product create New Dictionary if <>
    If product <> nextProduct Then
        Dim productGroup As New Dictionary
        productGroup.Add product, services
        Set services = New Collection
    End If
Next
End Sub

Edit
My Collection of services needs to be unique. As an example "Positive Pay" which belong to the "ARP" product group should only appear once in the collection.


texts: Seemingly redundant conditionals...or not?

texts:
I'm working on some code that has the following pattern of conditionals inside it. It doesn't look great, but it doesn't look terrible.

Please, shed some light on the underlying reason this is not passing my smell test. I'd love to see some alternatives. I'm guessing it's because it's completely ignoring a certain permutation.

Note: I'm asking this question with the intent of bettering the code, not code golf.

public class RoleManager
{
    public string Role { get; private set; }

    internal void SetRole(bool isManager, bool hasBackendAccess)
    {
        if (isManager && hasBackendAccess)
        {
            Role = "FullAccess";
        }
        else if (isManager)
        {
            Role = "Manager";
        }
        else if (hasBackendAccess)
        {
            Role = "LimitedBackend";
        }
    }
}


texts: A classy wine collection - Construction vs. Initialization

texts:
The following is for a chapter exercise in C++ Primer Plus, 6/e by Stephen Prata, for the first part of Chapter 14 which deals with code reuse through composition. The problem is to implement a Wine class (for modelling a wine collection) which contains a std::string (the wine name), an int and a Pair of std::valarrays to hold the vintages and bottles held of each. (Pair is a template class provided by the author.)

My question is whether I've got a good solution for the Wine constructors, or if I should be setting up my Pair in the initializer list (and what that would look like.)

Here's my header…

/**
* @file     winec.h
* @brief    Wine class with containment
*/

#ifndef WINEC_H_
#define WINEC_H_

#include <string>
#include <valarray>
#include "pair.h"

typedef std::valarray<int> ArrayInt;
typedef Pair<ArrayInt, ArrayInt> PairArray;

class Wine
{
private:
    std::string mLabel;
    PairArray holdings;
    int yearsHeld;

public:
    Wine();
    Wine(const char *l, int y);
    Wine(const char *l, int y, const int yrs[], const int bot[]);

    void getBottles();
    std::string & label();
    int sum() const;
    void show() const;
};

#endif

… and my implementation…

/**
* @file     winec.cpp
* @brief    Wine class with containment
*/

#include "winec.h"

Wine::Wine()
    : mLabel("Unnamed"), yearsHeld(0)
{
    holdings.first() = ArrayInt(0);
    holdings.second() = ArrayInt(0);
};

Wine::Wine(const char *l, int y)
    : mLabel(l), yearsHeld(y)
{
    holdings.first() = ArrayInt(0, y);
    holdings.second() = ArrayInt(0, y);
}

Wine::Wine(const char *l, int y, const int yrs[], const int bot[])
    : mLabel(l), yearsHeld(y)
{
    holdings.first() = ArrayInt(y);
    holdings.second() = ArrayInt(y);

    for (int i = 0; i < yearsHeld; i++)
    {
        holdings.first()[i] = yrs[i];
        holdings.second()[i] = bot[i];
    }
}

std::string & Wine::label()
{
    return mLabel;
}

void Wine::show() const
{
    using std::cout;
    using std::endl;

    cout << "Wine: " << mLabel << endl;
    cout << "\tYear\tBottles\n";
    for (int i = 0; i < yearsHeld; i++)
    {
        cout << "\t" << holdings.first()[i];
        cout << "\t" << holdings.second()[i];
        cout << endl;
    }
}

void Wine::getBottles()
{
    using std::cin;
    using std::cout;

    cout << "Enter holdings for " << yearsHeld << " years.\n";
    for (int i = 0; i < yearsHeld; i++)
    {
        cout << "Year: ";
        cin >> holdings.first()[i];
        cout << "Bottles: ";
        cin >> holdings.second()[i];
    }
}

int Wine::sum() const
{
    int sum = 0;
    for (int i = 0; i < yearsHeld; i++)
    {
        sum += holdings.second()[i];
    }
    return sum;
}

… along with the author's Pair<> template:

/**
* @file       pair.h
* @brief  Defining & using a Pair template
*/

#ifndef PAIR_H_
#define PAIR_H_

#include <iostream>
#include <string>

template <class T1, class T2>
class Pair
{
private:
  T1 a;
  T2 b;

public:
  T1 & first();
  T2 & second();
  T1 first() const { return a; }
  T2 second() const { return b; }
  Pair(const T1 &aval, const T2 &bval) : a(aval), b(bval) {}
  Pair() {}
};

template <class T1, class T2>
T1 & Pair<T1, T2>::first()
{
  return a;
}

template <class T1, class T2>
T2 & Pair<T1, T2>::second()
{
  return b;
}

#endif


texts:
I've tried to write my Property Container design-pattern implementation.

Could anybody, please, tell me, if this code is really what I intended to write (follows the Property Container design-pattern rules)? Is there anything that can be improved?

<?php

class PropertyContainer
{
    private $PropertyContainer = array();

    public function __construct() { }

    public function addProperty($k, $v)
    {
        for($i = 0; $i < count($this->PropertyContainer); $i++) { }
        $this->PropertyContainer[$k] = $v;
    }

    public function setProperty($k, $v)
    {
        while($this->PropertyContainer)
        {
            if(key($this->PropertyContainer) == $k) {
                $this->PropertyContainer[$k] = $v;
                return;
            }
            next($this->PropertyContainer);
        }
        echo "Key was not found";
    }

    public function getProperty($k)
    {
        //var_dump($this->PropertyContainer);
        foreach($this->PropertyContainer as $key => $val)
        {
            if($key == $k) { return $val; }
        }
        echo "Key was not found";
        return;
    }
}

$pc1 = new PropertyContainer();
$pc1->addProperty("myProperty1", 31);
$pc1->addProperty("myProperty2", 32);
$pc1->addProperty("myProperty3", 33);
$pc1->setProperty("myProperty2", 7);
echo $pc1->getProperty("myProperty1") . "
";
echo $pc1->getProperty("myProperty2") . "
";
echo $pc1->getProperty("myProperty3") . "
";

echo "
";

$pc2 = new PropertyContainer();
$pc2->addProperty("myProp1", 11);
$pc2->addProperty("myProp2", 11);
$pc2->addProperty("myProperty3", "Some String");
$pc2->setProperty("myProp2", 12);
echo $pc2->getProperty("myProp1") . "
";
echo $pc2->getProperty("myProp2") . "
";
echo $pc2->getProperty("myProperty3") . "
";

echo "
" . $pc2->getProperty("myProperty5") . "
";

?>


texts: Finding Facebook Friends on app, and not on app

texts:
This code gets all of a user's Facebook friends who use our app and returns a dictionary with keys that are their id's in our database and values that are a default connection level.

The code should also return all of the users Facebook friends who aren't using our app.

I made fb_id_on_app a dictionary of keys that are facebook_ids so that I could take advantage of the \$O(1)\$ lookup time for dictionaries. If I had made it a list it would have been an \$O(n)\$ where \$n\$ is the size of the list to check if the value was in there.

I'm sure there is a better way to do this any ideas. We are using Django framework as well.

DEFAULT_CONNECTION_LEVEL = 10
# Up to a whole day
UPDATE_FRIENDS_EVERY_N_MINUTES = 360

def find_friends_on_app(friends):
    """
    Checks each facebook id to find which facebook friends
    use our app
    """
    facebook_ids = [friend["id"] for friend in friends]
    dt_friends = User.objects.filter(
        facebook_id__in=facebook_ids)
    friends_on_app = {friend.id: DEFAULT_CONNECTION_LEVEL for friend in
                  dt_friends}
    fb_id_on_app = {friend.facebook_id: "value" for friend in
                dt_friends}
    friends_not_on_app = \
        [{'Name': friend.get("name"),
          'id': friend.get("id")} for friend in friends if
         fb_id_on_app.get(friend.get("id")) is None]
    return friends_not_on_app, friends_on_app


texts:
I am creating an application which will be testable(unit + integration). In this application I have a FileHelper static class,

public static class FileHelper
{
    public static void ExtractZipFile(Stream zipStream, string location)
    {
        ..................................
    }
    public static void CreatePageFolderIfNotExist(string directory)
    {
        .................................................
    }

    .......................................................
    .......................................................
}

But due to static I think it is not testable. How to make this class testable?


texts: LINQ for extracting N bottom items (async streams)

texts:
source.Bottom(n, x => x) should be the same as well known LINQ source.OrderBy(x => x).Take(n) but is more memory/run-time efficient as it does not keep all items in memory as OrderBy does:

public static class BottomN
{
    public static async IAsyncEnumerable<T> Bottom<T, TValue>(
        this IAsyncEnumerable<T> source, int number, Func<T, TValue> selector)
        where TValue : IComparable<TValue>
    {
        var list = new List<T>();
        await foreach(var item in source)
        {
            list.Insert(list.BestIndex(item, selector), item);
            if (list.Count > number)
                list.RemoveAt(number);
        }

        foreach (var item in list)
            yield return item;
    }

    static int BestIndex<T, TValue>(this IList<T> list, T value, Func<T, TValue> selector)
        where TValue : IComparable<TValue>
    {
        return bestIndex(0, list.Count);
        int bestIndex(int s, int e) =>
            s == e ? s :
                selector(list[(s + e) / 2]).CompareTo(selector(value)) > 0
                ? bestIndex(s, (s + e) / 2)
                : bestIndex((s + e) / 2 + 1, e);
    }
}

To test:

    [TestMethod]
    public async Task Keep_Three()
    {
        var values = new[] { 10, 22, 3, 55, 66, 100, 200, 2 };
        var bottom = await values.ToAsyncEnumerable().Bottom(3, v => v).ToArrayAsync();
        CollectionAssert.AreEqual(new int[] { 2, 3, 10 }, bottom);
    }


texts: Guess the presents someone will get by comparing wishlist attributes

texts:
#
# Guess the presents someone will get
# We compare a `wishlist` with many criteria to the `presents` and return an array with the names of the matching products.
#
def guess_gifts(wishlist, presents)

  wishlist.map do |w|
    w[:name] if presents.include? w.reject { |key| key == :name }
  end.compact.uniq

end

guess_gifts([

{:name => "mini puzzle", :size => "small", :clatters => "yes", :weight => "light"},
{:name => "toy car", :size => "medium", :clatters => "a bit", :weight => "medium"},
{:name => "card game", :size => "small", :clatters => "no", :weight => "light"}

],
[

{:size => "medium", :clatters => "a bit", :weight => "medium"},
{:size => "small", :clatters => "yes", :weight => "light"}

])

In particular, I'd like to know whether w.reject { |key| key == :name } is the best way to remove the :name item.  Is there any shorter or faster way to do so?  I am often very surprised with Ruby capacity to shorten processes, so I'm wondering.


texts:
I have an array of active record objects. All objects have an attribute result and the value of result can be either 'failed' or 'passed'.

My goal is to find out if all result attributes are identical. If not then I will have to return mixed but if they are then I return the value of the attributes.

I currently have this code:

if tests.map(&:result).uniq.count != 1
   'mixed'
else
   tests.first.result
end

But that first line is quite ugly. I'm sure there is a better way to find out if all results are identical or not but I can't think of any.


texts: Perform n mongodb updates at a time using SemaphoreSlim

texts:
I have a queue of jobs, and I want to process 20 at a time using asynchronous concurrency.

When processing a job, some updates in MongoDb are made an a file gets uploaded to a server, that's up to 1GB and would take about 40 seconds.

What do you think?

Program.cs

 public static void Main(string[] args)
{
    MainAsync(args).Wait();
}

 public static async Task MainAsync(string[] args)
    {
        var serviceCollection = new ServiceCollection();
        ConfigureServices(serviceCollection);

        var serviceProvider = serviceCollection
            .AddLogging()
            .AddAutoMapper(typeof(Program))
            .BuildServiceProvider();

        await serviceProvider.GetService<App>().Run(20);
    }

App.cs

public class App
{
    private readonly IQueueService _queueService;
    private readonly IUploadService _uploadService;
    private SemaphoreSlim _throttle;

    public App(IQueueService queueService, IUploadService uploadService)
    {
        _queueService = queueService;
        _uploadService = uploadService;
    }

    public async Task Run(int initialCount = 3)
    {
        _throttle = new SemaphoreSlim(initialCount);

        var jobs = await _queueService.GetQueue();

        var tasks = jobs.Select(ProcessJob);
        await Task.WhenAll(tasks);

        Console.WriteLine("Upload finished...");
        Console.ReadKey();
    }

    private async Task ProcessJob(JobDto JobDto)
    {
        await _throttle.WaitAsync();
        try
        {
            // Process file
            Guid.TryParse(JobDto.JobName, out var jobId);
            var isUploaded = await _uploadService.Upload(JobDto.CreatedBy, jobId);

            // Update collection
            await _queueService.DeleteJobQueue(JobDto.Id);
        }
        finally
        {
            _throttle.Release();
        }
    }
}


texts: Solving a one-dimensional Euler equation for fluid dynamics

texts:
I just wrote a program to solve one dimensional Euler equation for fluid dynamics. Attached is a snippet of the vtune profile result for one of the function.
There are a few things which looks weird to me. For example, difference in line 72 takes more time than division in line 70. Also line 70 takes more time than 69 which include a sqrt! Can anyone explain the discrepancy? Also suggestion to improve (in terms of performance) this piece of code is welcome.

This particular routine is called many times in the code so I want this to be as fast as possible.

Additional information:

This module is part of a multi-threaded program (using OpenMO).
I am using Intel C++ compiler, icpc, with -O3.
My ultimate aim is to run this code on Xeon-Phi.

Function

__declspec(vector) void roeflux(double rhol, double rhor, double ul, double ur, double pl, double pr,
                double *f_0, double *f_1, double *f_2){
  double el = pl/(GAMMA_M) + 0.5f*rhol*ul*ul;
  double er = pr/(GAMMA_M) + 0.5f*rhor*ur*ur;
  double hl = (el + pl)/rhol;
  double hr = (er + pr)/rhor;

  double sqrtrhol = sqrt(rhol);
  double sqrtrhor = sqrt(rhor);
  double den_inverse = 1/(sqrtrhol + sqrtrhor);
  double uavg = (sqrtrhol*ul + sqrtrhor*ur)*den_inverse;
  double havg = (sqrtrhol*hl + sqrtrhor*hr)*den_inverse;
  double cavg = sqrt(GAMMA_M*(havg - 0.5f*uavg*uavg));
  double cavg_inverse = 1.0f/cavg;

  double d1 = rhor - rhol;
  double d2 = rhor*ur - rhol*ul;
  double d3 = er - el;

  double alpha_2 = GAMMA_M*((havg - uavg*uavg)*d1 + uavg*d2 - d3)*cavg_inverse*cavg_inverse;
  double alpha_3 = 0.5f*(d2 + (cavg - uavg)*d1 - cavg*alpha_2)*cavg_inverse;
  double alpha_1 = d1 - alpha_2 - alpha_3;

  double lambda_1 =  fabs(uavg - cavg);
  double lambda_2 =  fabs(uavg);
  double lambda_3 =  fabs(uavg + cavg);

  double f1 = lambda_1*alpha_1 + lambda_2*alpha_2 + lambda_3*alpha_3;
  double f2 = lambda_1*alpha_1*(uavg-cavg) + lambda_2*alpha_2*uavg + lambda_3*alpha_3*(uavg+cavg);
  double f3 = lambda_1*alpha_1*(havg-cavg*uavg) + 0.5f*lambda_2*alpha_2*uavg*uavg + lambda_3*alpha_3*(havg+cavg*uavg);

  *f_0 = 0.5f*((rhol*ul + rhor*ur) - f1);
  *f_1 = 0.5f*((rhol*ul*ul + pl + rhor*ur*ur + pr) - f2);
  *f_2 = 0.5f*(ul*hl*rhol + ur*hr*rhor - f3);
}


texts:
I am new to C, and this is my first attempt at creating a linked list.

If anyone has a minute and could point out any errors or bad practices in this small linked list program, it would be really helpful.

note:
I'm using the get_choice function to run a loop to either delete, insert, locate, print-out links, or exit.

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

struct Link_Data {

    int value;

    struct Link_Data *prev;

    struct Link_Data *next;
};

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

    char declare[] = "Begin...";
    printf ("%s\n", declare);

    struct Link_Data *head = malloc( sizeof *head );
    head->prev = NULL;
    head->next = NULL;
    head->value = 0;
    get_choice(head);

    return 0;
}

int get_choice(struct Link_Data *head) {

    int choice;
    int value;

    while ( true ) {

        printf ("Enter 1 to delete, 2 to insert, 3 to locate, 4 to print_all, or 0 to quit: ");
        scanf ("%d", &choice);

        switch (choice) {

            case(1):
                printf ("Enter value: ");
                scanf ("%d", &value);
                delete_node(head, value);
                break;

            case(2):
                printf ("Enter value: ");
                scanf ("%d", &value);
                insert_node(head, value);
                break;

            case(3):
                printf ("Enter value: ");
                scanf ("%d", &value);
                locate_node(head, value);
                break;

            case(4):
                printf ("Printing list...\n");
                print_links(head);
                break;

            case(0):
                return 0;
        }
    }
}

int delete_node(struct Link_Data *node, int value) {

    if (node->next == NULL && node->prev == NULL) {

        printf ("List is empty!\n");
        return 0;
    }

    else if (node->next == NULL && node->value != value) {

        printf ("Value %d not in list!\n", value);
        return 0;
    }

    else {
        if (node->value == value && node->prev != NULL) {

            printf ("Deleting %d...\n", value);
            struct Link_Data *prev = node->prev;
            prev->next = node->next;
            free(node);
        }
        else {
            delete_node(node->next, value);
        }
    }
    return 0;
}

int insert_node(struct Link_Data *node, int value) {

    if (node->next == NULL) {

        printf ("Inserting %d...\n", value);
        struct Link_Data *new_link = malloc( sizeof *new_link );

        new_link->value = value;
        new_link->prev = node;
        new_link->next = NULL;

        node->next = new_link;
    }

    else {

        insert_node(node->next, value);
    }

    return 0;
}

int locate_node(struct Link_Data *node, int value) {

    if (node->next == NULL && node->value != value) {

        printf ("Value %d not in list!\n", value);
    }
    else {
        if (node->value == value) {

            printf ("Locating %d...\n", value);
            printf ("Value %d in list!\n", value);
        }
        else {

            locate_node(node->next, value);
        }
    }

    return 0;
}

int print_links(struct Link_Data *node) {

    if (node->prev == NULL && node->next == NULL) {

        printf ("List is empty!\n");
        return 0;
    }
    else {
        if (node->prev != NULL) {

            printf ("Value: %d\n", node->value);
        }
        if (node->next == NULL) {

            return 0;
        }
        else {

            print_links(node->next);
        }
    }

    return 0;
}


texts:
In an interview I was asked to solve the following problem:

  find a subarray with max sum

I have written a piece of code for the same.  I need your help in reviewing this code.

package com.ankit.rnd;

public class MaxSubArrSum {

    int largestSum=0;
    int previousLargestSum=0;

    public static void main(String[] args) {
        // int [] array = {-2,1,-3,4,-1,2,1,-5,4};
        int [] array = {-5,1,-3,7,-1,2,1,-4,6};
        // int [] array = {-2,-3,-4,2};

        MaxSubArrSum obj = new MaxSubArrSum();

        for(int varindex=0;varindex<array.length;varindex++){

            // int sumis =new MaxSubArrSum().findSum(varindex,array);
            // System.out.println("sumis::" +sumis);
            obj.splitCurrentArray(varindex,array);
        }
    }

    private void splitCurrentArray(int in, int[] arr) {

        int [] tempArr = new int[arr.length-in];
        for(int i=in;i<arr.length;i++){
            if(in ==0){
                tempArr[i] = arr[i];
            }
            else{
                tempArr[i-in] = arr[i];
            }
        }

        int sum =findSum(in, tempArr);
        System.out.println("Previous Largest Sum::" + previousLargestSum);
        System.out.println("Largest Sum found:" + sum);
    }

    @SuppressWarnings("unused")
    private int findSum(int start,int [] array) {

        int[] currentArray ={};

        int [] largestArray = new int[array.length];
        int sum=0;
        /*for(int i=start;i<array.length;i++){*/
            for(int i=0;i<array.length;i++){
            //a little inefficient here as it always create an array with size more than total number of elements that should be there in the temp array.
            int psuedoIndex=i;
            if(start==0){
                currentArray = new int[i + 1];
                for (int j = 0; j <= i; j++) {
                    currentArray[j] = array[j];

                    psuedoIndex=psuedoIndex+1;
                }
            }
            else {
                currentArray = new int[i+1];
                for (int j = 0; j <= i; j++) {
                    currentArray[j] = array[j];

                    /*
                     * if(psuedoIndex == array.length){ //needs a fix. as we
                     * have reached the end of the array. //currentArray[j] =
                     * array[psuedoIndex-1]; currentArray[j] = 0; break; } else{
                     *
                     * currentArray[j] = array[psuedoIndex]; is commented out
                     * because it missed the element in the previous array.
                     *
                     *
                     * //currentArray[j] = array[psuedoIndex]; currentArray[j] =
                     * array[j]; }
                     */

                    psuedoIndex=psuedoIndex+1;
                }
            }

            if((sum = calculate(currentArray))>largestSum){
                previousLargestSum=largestSum;
                largestSum=sum;
                for(int k=0;k<currentArray.length;k++){
                    System.out.print(currentArray[k] + "|");

                }
                System.out.println("");
            }
        }
        return largestSum;
    }

    private int calculate(int [] currentArr){
        int sumOfElements =0;
        for(int index=0;index<currentArr.length;index++){
            sumOfElements +=currentArr[index];

        }
        //System.out.println("sum is:" + sumOfElements);
        return sumOfElements;
    }
}


texts: Group by and sum query on multiple columns

texts:
var fpslist = db.FPSinformations.Where(x => x.Godown_Code != null && x.Godown_Code == godownid).ToList();
var data1 = fpslist.GroupBy(x => x.Ration_Card_Type1)
    .Select(x => new
    {
        CardType_Name = x.Key,
        CardType_Count = x.Sum(y => y.Ration_Card_Count1)
    }).ToList();
var data2 = fpslist.GroupBy(x => x.Ration_Card_Type2)
    .Select(x => new
    {
        CardType_Name = x.Key,
        CardType_Count = x.Sum(y => y.Ration_Card_Count2)
    }).ToList();
var data3 = fpslist.GroupBy(x => x.Ration_Card_Type3)
    .Select(x => new
    {
        CardType_Name = x.Key,
        CardType_Count = x.Sum(y => y.Ration_Card_Count3)
    }).ToList();
var data4 = fpslist.GroupBy(x => x.Ration_Card_Type4)
    .Select(x => new
    {
        CardType_Name = x.Key,
        CardType_Count = x.Sum(y => y.Ration_Card_Count4)
    }).ToList();
var data5 = fpslist.GroupBy(x => x.Ration_Card_Type5)
    .Select(x => new
    {
        CardType_Name = x.Key,
        CardType_Count = x.Sum(y => y.Ration_Card_Count5)
    }).ToList();

var GodownRCCount = data1.Where(x => x.CardType_Name != null).ToList();
var GodownRCCounts = GodownRCCount;
GodownRCCount = data2.Where(x => x.CardType_Name != null).ToList();
GodownRCCounts.AddRange(GodownRCCount);
GodownRCCount = data3.Where(x => x.CardType_Name != null).ToList();
GodownRCCounts.AddRange(GodownRCCount);
GodownRCCount = data4.Where(x => x.CardType_Name != null).ToList();
GodownRCCounts.AddRange(GodownRCCount);
GodownRCCount = data5.Where(x => x.CardType_Name != null).ToList();
GodownRCCounts.AddRange(GodownRCCount);

I have 10 columns in my database like this:

Ration_Card_Type1
Ration_card_count1
Ration_Card_Type2
Ration_card_count2
Ration_Card_Type3
Ration_card_count3
Ration_Card_Type4
Ration_card_count4
Ration_Card_Type5
Ration_card_count5

Now what I want is to get the sum of Ration_Card_Counts and its type from its type.

Expected output:

CardType_Name
CardType_Count

It works fine, but I want to optimize it in max possible way as this will be inside a loop.


texts: refactor function so same code is written only once

texts:
I have this code

@objc func didClickActionButton(sender: UITapGestureRecognizer) {

    if let contents = contentList {

      if contents[currentScreenIndex].customMeta["permission-location"] != nil {
        //request Permission
        ApiHelper.shared.initLocationHelperWithBeacon()
      }
      if contents[currentScreenIndex].customMeta["permission-notification"] != nil {
//        PushNotificationHelper.requestNotificationAuthorization { }
        PushNotificationHelper.requestNotificationAuthorization {
          DispatchQueue.main.async {
            if self.currentScreenIndex == contents.count - 1 {
                self.finishOnboarding()
              return
            }
           self.currentScreenIndex+=1
           self.showScreenAtPosition(position: self.currentScreenIndex)
          }
        }
        return
      }
      if currentScreenIndex == contents.count - 1 {
        finishOnboarding()
        return
      }
      currentScreenIndex+=1
      showScreenAtPosition(position: currentScreenIndex)
    }
  }

As you can see I have the same code in the DispatchQueue.main.async as I have at the bottom at the func. Is there anyway to refactor this so I don't write the same code twice? Is it even worth it to refactor this?


texts: Project Euler # 49 Prime permutations in Python

texts:
The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual
in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are
permutations of one another.

There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this
property, but there is one other 4-digit increasing sequence.

What 12-digit number do you form by concatenating the three terms in this sequence?

from time import time

def sieve(n):
    """generates primes up to n."""
    s = [True] * (n + 1)
    for p in range(2, n):
        if s[p]:
            yield p
            for i in range(p * p, n, p):
                s[i] = False

def is_permutation(n1, n2):
    """returns True if n1 is permutation of n2"""
    to_str_1 = str(n1)
    to_str_2 = str(n2)
    if n1 == n2:
        return False
    to_str_1_digits = {digit: to_str_1.count(digit) for digit in to_str_1}
    to_str_2_digits = {digit: to_str_2.count(digit) for digit in to_str_2}
    if not to_str_1_digits == to_str_2_digits:
        return False
    return True

def get_permutations(n):
    """generates tuples of 3 permutations each within range n."""
    primes = set(sieve(n))
    for prime1 in primes:
        for prime2 in primes:
            if is_permutation(prime1, prime2):
                for prime3 in primes:
                    if is_permutation(prime3, prime1) and is_permutation(prime3, prime2):
                        yield prime1, prime2, prime3

def check_subtraction(n):
    """checks permutations within range n for subtraction rules.
    returns valid permutations."""
    permutations = get_permutations(n)
    for x, y, z in permutations:
        if abs(x - y) == abs(y - z):
            return x, y, z

if __name__ == '__main__':
    start_time = time()
    x, y, z = sorted(check_subtraction(10000))
    print(str(x) + str(y) + str(z))
    print(f'Time: {time() - start_time} seconds.')


texts: Count the occurrence of each unique word in the file

texts:
I've been doing a task for an interview that I will have soon.
The requirement is to code the following problem in C#.

  Write a program (and prove that it works) that: Given a text file, count the occurrence of each unique word in the file.
  For example; a file containing the string “Go do that thing that you do so well” should find these counts:
  1: Go
  2: do
  2: that
  1: thing
  1: you
  1: so
  1: well

I coded my solution and it's working fine for the tests I gave.

I'm looking for any ways that I can improve my code and to get feedback on the solution. Is there's any way I could to the problem more efficiently.

Thank you in advance.

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace CountOccurrence
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = System.IO.File.ReadAllText(@"F:\Ex\Myfile.txt");              // User ReadAllText to copy the file's text into a string
            string textToLower = text.ToLower();                                        // Converts the string to lower case string
            Regex reg_exp = new Regex("[^a-z0-9]");                                     // Regular expressions to replace non-letter and non-number characters with spaces. It uses the pattern [^a-z0-9].The a-z0-9 part means any lowercase letter or a digit.
            textToLower = reg_exp.Replace(textToLower, " ");                            // The code uses the Regex object’s Replace method to replace the characters that match the pattern with a space character.
            string[] Value = textToLower.Split(new char[] {' '},
            StringSplitOptions.RemoveEmptyEntries);                                     // Split the string and remove the empty entries

            Dictionary<string, int> CountTheOccurrences = new Dictionary<string, int>(); // Create a dictionary to keep track of each occurrence of the words in the string
            for (int i = 0; i < Value.Length; i++)                                       // Loop the splited string
            {
                if (CountTheOccurrences.ContainsKey(Value[i]))                           // Check if word is already in dictionary update the count
                {
                    int value = CountTheOccurrences[Value[i]];
                    CountTheOccurrences[Value[i]] = value + 1;
                }
                else                                                                     // If we found the same word we just increase the count in the dictionary
                {
                    CountTheOccurrences.Add(Value[i], 1);
                }
            }

            Console.WriteLine("The number of counts for each words are:");
            foreach (KeyValuePair<string, int> kvp in CountTheOccurrences)
            {
                Console.WriteLine("Counts: " + kvp.Value + " for " + kvp.Key);           // Print the number of counts for each word
            }
            Console.ReadKey();
        }
    }
}


texts:
I'm using 2 objects inside my class. My actions are almost identical, however I want to return 2 different data types and both are slightly different from each other.

import requests

class coins:

    def coins_arr(self):
        params = {'limit': 10, 'convert': 'USD'}
        data = requests.get('https://api.coinmarketcap.com/v1/ticker/?%s' % params).json()
        coinsData = []
        for objects in data:
            for k in objects.keys():
                if k == 'id':
                    coinsData += objects[k].split()
        #returns array of coin names
        return sorted(coinsData)

    def coins_dict(self):
        params = {'limit': 10, 'convert': 'USD'}
        data = requests.get('https://api.coinmarketcap.com/v1/ticker/?%s' % params).json()
        coinsDict = {}
        for objects in data:
            for k,v in objects.items():
                if k == 'id':
                    coinsDict.update({objects[k]:objects['price_usd']})
        #returns dictionary with name:price
        return coinsDict

d = coins()

print (d.coins_arr())

I thought of returning the coins_dict.keys(), but it won't return me it in a sorted order. I am not sure if I can implement a lambda function when I call the class object.


texts: Use an optionally passed-in block without repeating yourself

texts:
I need to open and read several files for a project. Some of them are plain text files, and I just want a standard File.open to read from. One of them is an XML file, and I want it automatically loaded into Nokogiri in the following way:

xml = File.open("#{LOCATION}/#{filename}.xml"){|f| Nokogiri::XML(f){|config| config.noblanks}}

So I created a function that takes a pattern to select a file, and then optionally opens it with a block so that I can pass in the Nokogiri block above in the case of the xml file.

How do I reduce the repetition in the code?

# in read_xml...
xml = file_from_pattern(XML_PATTERN){|f| Nokogiri::XML(f){|config| config.noblanks}}

# in read_audit...
audit_lines = file_from_pattern(AUDIT_PATTERN).readlines

def file_from_pattern(pattern)
  file_name = Dir.entries("#{LOCATION}").select{|f| f =~ pattern}[0]
  if block_given?
    yield File.open("#{LOCATION}/#{file_name}")
  else
    File.open("#{LOCATION}/#{file_name}")
  end
end


texts: Computation of inter-grid distance array for 2D lattice

texts:
I have a 2D lattice with U × U number of grids. My goal is to create an array – of shape U^2 × U^2 – where each entry denotes the least-distance between each grid and any other grid.

Currently, for U=60, my Python script takes ~5 minutes to complete. As a novice programmer, I suspect there must be a more efficient approach – I've read about performance issues related to numpy loops. My objective is to handle U=1000.

import numpy as np
np.random.seed(13)
import matplotlib.pyplot as plt
import time

start_time = time.time()

U = 60

def FromGridToList(i_, j_):
    return i_*U + j_

def FromListToGrid(l_):
    i = np.floor(l_/U)
    j = l_ - i*U
    return np.array((i,j))

Ulist = range(U**2)

dist_array = []
for l in Ulist:
    print l, 'of', U**2
    di = np.array([np.abs(FromListToGrid(l)[0]-FromListToGrid(i)[0]) for i, x in enumerate(Ulist)])
    di = np.minimum(di, U-di)

    dj = np.array([np.abs(FromListToGrid(l)[1]-FromListToGrid(i)[1]) for i, x in enumerate(Ulist)])
    dj = np.minimum(dj, U-dj)

    d = np.sqrt(di**2+dj**2)
    dist_array.append(d)

dist_array = np.vstack(dist_array)
print time.time() - start_time, 'seconds'


texts:
def age_post(post) do

    birthday = Timex.date({post.birthday_year, post.birthday_month, post.birthday_day})
    now = Date.now

    years = Timex.diff(now, birthday, :years)

    Integer.to_string(years) <> " ans"

  end

I'm quite new with the elixir language, I'm pretty sure you can get the same result than that code in one line.


texts:
I have to generate a random number from a range with exceptions held in a bool array, is there a way to do it without a loop depending on probability?
There is also a potential infinite loop here if all values are false.
Any suggestions?

    bool[] paths = InnateChannels(channelID, channelOrientation);

    bool done = false;
    int iDirection = 0;
    while (!done)
    {
        iDirection = Random.Range(0, 4);
        if (paths[iDirection])
            done = true;
    }
    direction = DirectionToVector(iDirection);


texts:
I have implemented the kaprekar's constant algorithm in c#, and I want your feedback.

Here is how the algorithm works:

it takes a number of 4 digits (e.g: 5823)
we order that number in ascendent and descendent order, which gives as two numbers (e.g: 8532 and 2358).
we subtract the larger number from the smaller number (e.g: 8532 - 2358 = 6174)
we repeat this operation until the difference is equal to 6174.

Example:

step 1:

 number = 8532
    cpt = 0 // the number of repeatation util the number became equal to 6174.
    1) asc  = 2358
    2) desc = 8532
    3) Difference = 6174
    4) cpt++
    5) Repeating above steps as difference is not equal to number.

step2:

 number = 6174
     1) asc  = 1467
     2) desc = 7641
     3) Difference = 6174
     4) c++
     5) return cpt and stopping here as difference is equal to number.

Here is my Code:

1- recursive method:

   int KaprekarsConstant(int num, int target)
        {
            if (num.ToString().Length != 4)
                throw new ArgumentException();

            var desendingOrder = num.ToString().OrderByDescending(a => a);
            var acendingOrder = num.ToString().OrderBy(a => a);

            int maxPart = int.Parse(new string(desendingOrder.ToArray()));
            int minPart = int.Parse(new string(acendingOrder.ToArray()));

            var diff = maxPart - minPart;
            if (diff == target) return 1;
            return 1+ KaprekarsConstant(diff, target);
        }

2- non-recursive method:

 int KaprekarsConstant2(int num, int target)
            {
                int cpt = 0;
                if (num.ToString().Length != 4)
                    throw new ArgumentException();

                while (true)
                {
                    var desendingOrder = num.ToString().OrderByDescending(a => a);
                    var acendingOrder = num.ToString().OrderBy(a => a);

                    int maxPart = int.Parse(new string(desendingOrder.ToArray()));
                    int minPart = int.Parse(new string(acendingOrder.ToArray()));

                    var diff = maxPart - minPart;
                    cpt++;
                    if (diff == target) return cpt;
                    num = diff;
                }
            }

Code test:

  public static void Main(string[] args)
        {
            Console.WriteLine(KaprekarsConstant(6174, 6174)); //cpt =1
            Console.WriteLine(KaprekarsConstant(3524, 6174)); //cpt =3
            Console.WriteLine(KaprekarsConstant(2324, 6174)); //cpt =3
            Console.WriteLine(KaprekarsConstant(9812, 6174)); //cpt =2
            Console.ReadLine();
        }

Thanks in advance for your help!


texts: Lock Using “Interlocked” vs lock Statement (“Monitor”) (Followup)

texts:
This is a followup to a previous question.

Considering:

Interlocked.CompareExchange generates a memory barrier,
Intended to be used with very fast operations (like generating an
id),
SpinWait starts sleeping in milliseconds after 10 or so spins (and
does some other smart stuff),

What are characteristics (pros & cons) of this code?

public class SpinMutex
{
    const long Locked = 1;
    const long Unlocked = 0;

    long _locked;

    public SpinMutex() { _locked = Unlocked; }

    /*public*/
    void Lock()
    {
        SpinWait.SpinUntil(() => Interlocked.CompareExchange(ref _locked, Locked, Unlocked) == Unlocked);
    }

    /*public*/
    bool Lock(int millisecondsTimeout)
    {
        return SpinWait.SpinUntil(() => Interlocked.CompareExchange(ref _locked, Locked, Unlocked) == Unlocked, millisecondsTimeout);
    }

    /*public*/
    bool Lock(TimeSpan timeout)
    {
        return SpinWait.SpinUntil(() => Interlocked.CompareExchange(ref _locked, Locked, Unlocked) == Unlocked, timeout);
    }

    /*public*/
    void Unlock()
    {
        Interlocked.CompareExchange(ref _locked, Unlocked, Locked);
    }

    public IDisposable EnterScope()
    {
        return new Scope(this);
    }

    public IDisposable EnterScope(int millisecondsTimeout)
    {
        return new Scope(this, millisecondsTimeout);
    }

    class Scope : IDisposable
    {
        SpinMutex _spinMutex;
        int _millisecondsTimeout;
        bool _locked;
        bool _shouldDispose;

        internal Scope(SpinMutex spinMutex, int millisecondsTimeout = -1)
        {
            _spinMutex = spinMutex;
            _millisecondsTimeout = millisecondsTimeout < -1 ? -1 : millisecondsTimeout;
            _locked = false;
            _shouldDispose = true;

            try
            {
                if (_millisecondsTimeout < 0) _spinMutex.Lock();
                else if (!_spinMutex.Lock(_millisecondsTimeout)) throw new TimeoutException();
                else _locked = true;
            }
            catch
            {
                Dispose();
                _shouldDispose = false;
                throw;
            }
        }

        public void Dispose()
        {
            if (!_shouldDispose) return;
            if (_millisecondsTimeout < 0) _spinMutex.Unlock();
            else if (_locked) _spinMutex.Unlock();
        }
    }
}

And would be used like this:

static readonly SpinMutex MySpinMutex = new SpinMutex();

static void Process1()
{
    using (MySpinMutex.EnterScope()) { /* ... */ }
}

static void Process2()
{
    using (MySpinMutex.EnterScope()) { /* ... */ }
}

Instances of SpinMutex can be accessed from different Threads/Tasks safely.


texts: Improved RandomGenerator with nextPrime() method

texts:
I am trying to implement a method that generates a random prime number between a given range.

I have tried using a simple method to find whether a number is prime or not, advanced simple method, Wilson's method and I ended up with sieve of Eratosthenes as soon as my code based on this algorithm is faster than all of previous methods for finding if a number is prime or not.

Although the efficiency is satisfying, I know that there is an implementation that works without creating an array and with the code run even faster, but I don't know how to do this, so my question is obvious.

import acm.program.*;
import acm.util.RandomGenerator;

public class exercise4 extends Program {
public int nextPrime(int n){                                          //sieve of Eratosthenes
        final RandomGenerator rgen = RandomGenerator.getInstance();
        boolean[] array = new boolean[n];
        for (int i=2; i<n;i++) {
            array[i]=true;
        }
        int i=2;
        while (i<Math.sqrt(n)) {
            if (array[i]==true) {
                int m=i*i;
                int j=0;
                while (m+j*i<n) {
                    array[m+j*i]=false;
                    j++;
                };
            };
            i++;
        };
        int random;
        do {
            random=rgen.nextInt(n);
        } while(array[random]==false);
        return random;
    }
    public void run(){
        //long start = System.currentTimeMillis();
        println(nextPrime(2_000_000));
        //long elapsedTimeMillis = System.currentTimeMillis()-start;
        //float elapsedTimeSec = elapsedTimeMillis/1000F;
        //println("Completed in: "+elapsedTimeSec+" seconds.");
    }
}


texts:
All models are in the model namespace and follow a naming convention.  This makes it easy to consolidate control into cType() as shown below.

All control passes through cTYpe() which calls the correct model.  It does this by way of the type parameter which is set by the call back function for the specified event.

Calls to Model

model[type].pre()

model[type].post()

Controller and Model

var model = {};
model.user_try =
{
    pre : function()
    {
    },
    post : function( text )
    {
    }
};
function cType( type, param )
{
    var m_response = model[type].pre();
    if( m_response )
    {
         cServer( param, function( text, type ){ model[type].post( text ); }, type );
         return true;
    }
    else
    {
         return m_response;
    }
}

PostScript

Because this is a small prototype/app I have preferences or things I will consider when I will have a working prototype, they are - testing, try/catch/throw handling of errors, advanced abstractions / design patterns, defensive coding against programmer error / malicious users.  Will add these later if the project matures.


texts:
I'm trying to generate a fresh XML file using Perl XML::Mini::Document. It's working fine, but I don't know whether it's the right way to do it.  Performance is the problem for me; it takes more time when the when record count increases.

Is there any other module better doing than this one in performance and easier way?

#!/usr/bin/perl -w

use warnings;
use XML::Mini::Document;

my $outfile = "D:/Test.xml";

my $nSequence = 1000;
my $sRandom_Name = "";
my $sRandom_Desc = "";
my $newDoc = XML::Mini::Document->new();
my $newDocRoot = $newDoc->getRoot();
my $xmlHeader = $newDocRoot->header('xml');
$xmlHeader->attribute('version', '1.0');
$xmlHeader->attribute('encoding', 'UTF-8');

my $records= $newDocRoot->createChild('records');

for(0..9) {

   for(1..6) {
      $sRandom_Name = $sRandom_Name.(chr(int(rand(25) + 65)));
   }
   for(1..15) {
      $sRandom_Desc = $sRandom_Desc.(chr(int(rand(25) + 97)));
   }

   my $record = $records->createChild('record');

   $record->createChild('ID')->text($nSequence=$nSequence+1);
   $record->createChild('Name')->text($sRandom_Name);
   $record->createChild('Desc')->text($sRandom_Desc);

   print $newDoc->toFile($outfile);
}

My output should look like this one:

<?xml version="1.0" encoding="UTF-8" ?>
   <records>
    <record>
         <ID>1001</ID>
         <Name>ASDSDF</Name>
         <Desc>ASDFsdsdfcwefSC</Desc>
      </record>
      <record>
         <ID>1002</ID>
         <Name>KDFNND</Name>
         <Desc>WEFsdssccwefSC</Desc>
      </record>
      <record>
         <ID>1003</ID>
         <Name>PORJDX</Name>
         <Desc>XceFsdsdfcASmsd</Desc>
      </record>
      .
      .
      .
   </records>


texts: Tracking the stability of a website using ping monitor

texts:
I'm new to coding and made a small Node script that checks when a website is down because of high traffic. It's a website that sells tickets and I don't want to press F5 every 10 seconds to check if the website works again.

Because I send a ping so often I sometimes receive something back from the website. But when I check it again a couple of seconds later I get a request timeout again.

So I made a counter to track how stable the website is. If I receive a request timeout subtract from the counter.

It works, but I was wondering if there is a better way or solution to do this. Because I'm still new I don't have much experience with other solutions to this sort of problem.

This is my code:

const Monitor = require('ping-monitor');
const sendEmail = require('./Email.js')

const myMonitor = new Monitor({
  website: 'https://www.pathe.nl/',
  title: 'Pathe',
  interval: 0.1 // minutes, so 0.1 is 6 seconds
});

let counterUp = 0;

myMonitor.on('up', function (res, state) {
  counterUp++
  console.log('counter is ' + counterUp)
  console.log('Yay!! ' + res.website + ' is up.');

  // send email when script made sure the website is really up and stable. Otherwise we receive an email when the website isn't fully up and running. Because we send a ping every 6 seconds.
  if (counterUp == 20) {
    sendEmail(myMonitor.title)
    console.log('sending email')
  }
});

myMonitor.on('down', function (res) {
  counterUp--
  console.log('counter is ' + counterUp)
  console.log('Oh Snap!! ' + res.website + ' is down! ' + res.statusMessage);
});

myMonitor.on('stop', function (website) {
  console.log(website + ' monitor has stopped.');
});

myMonitor.on('error', function (error) {
  console.log(error);
});


texts:
I have been trying to improve my Python coding and was just wondering if there was a more pythonic way to perform what I have done so far, namely around the date in the main() function.
import datetime
import sybase

account_list = []

def get_date(): # Date -1 day unless Monday then -3 days
    d = datetime.date.today()
    if d.weekday() == 0:
        date = d - datetime.timedelta(days=3)
        return date
    else:
        date = d - datetime.timedelta(days=1)
        return date

def get_unique_accounts(date):
    conn = sybase.Connection('')
    c = conn.cursor()
    c.execute("SELECT DISTINCT acct from accounts WHERE date = @date", {"@date": date})
    result = c.fetchall()
    for row in result:
        account_list.append(row[0])
    c.close()
    conn.close()

def check_balance(date):
    conn = sybase.Connection('')
    c = conn.cursor()
    c.execute("SELECT TOP 1 name,balance from balance WHERE date = @date", {"@date": date})
    result = c.fetchone()
    c.close()
    conn.close()
    return result

def main():
    date = get_date()
    get_unique_accounts(date) # This will be used for future functions
    check_balance(date)

if __name__ == "__main__":
    main()


texts: Triggerful Ruby Gem: create dynamic callbacks to methods

texts:
The main purpose of Ruby is to be readable. I hope I did a good job with this gem I made. If there's any kind of suggestion of how to make this better, then please tell me.

class Trigger
  def initialize event, *callbacks
    @callbacks = callbacks
    @event = event

    if @callbacks[0].is_a? TrueClass
      @progression = true
      @callbacks.delete_at(0)
    elsif @callbacks[0].is_a? FalseClass
      @progression = false
      @callbacks.delete_at(0)
    else
      @progression = false
    end
  end

  def trigger(*args)
    case @event
    when Proc
      event_data = @event.call
    when Method
      event_data = @event.call
    else
      event_data = self.method(@event).call(*args)
    end
    @callbacks.each do |callback|
      if callback.instance_of? Trigger
        if @progression
          callback.trigger(*args, event_data)
        else
          callback.trigger(*args)
        end
      else
        case callback
        when Proc
          if @progression
            callback.call(*args, event_data)
          else
            callback.call(*args)
          end
        when Method
          if @progression
            callback.call(*args, event_data)
          else
            callback.call(*args)
          end
        else
          if @progression
            method(callback).call(*args, event_data)
          else
            method(callback).call(*args)
          end
        end
      end
    end
  end

  #triggers the callbacks without executing the original method
  def silent_trigger(*args)
    @callbacks.each do |callback|
      if callback.instance_of? Trigger
        callback.trigger(*args)
      else
        case callback
        when Proc
          callback.call
        when Method
          callback.call
        else
          method(callback).call(*args)
        end
      end
    end
  end

  # add callback(s) to instance
  def add(*callbacks)
    @callbacks.concat callbacks
  end

  def insert(index, *callbacks)
    @callbacks.insert(index, callbacks)
  end

  # remove callback(s) from instance
  def remove(*callbacks)
    callbacks.each do |callback|
      @callbacks.delete_at(@callbacks.index(callback) || @callbacks.length)
    end
  end

  def delete_at(index)
    @callbacks.delete_at(index)
  end

  def remove_all
    @callbacks = []
  end

  # fetch info from instance
  def index(callback)
    @callbacks.index(callback)
  end

  def event_name
    @event
  end

  def list
    @callbacks
  end
end

And if you want to try it out, here's a quick little console program to show you how it works:

$foobar = 0

def foo
  $foobar += 1
end

def bar
  puts $foobar
end

# create Trigger and callback, then trigger the Trigger
_foo = Trigger.new(:foo, :bar)
_foo.trigger

# create a method to determine if bar has been called before
$bar_called? = false
def bar_called
  $bar_called = true
end

# create a callback for the callback
_bar = Trigger.new(:bar, :bar_called)

# replace old callback with new one (note: you can use Methods, Procs, Symbols, Strings, or other Triggers too)
_foo.remove(:bar)
_foo.add(_bar)

# methods are not called when added to Trigger callbacks, only when triggered
puts $bar_called?
_foo.trigger
puts $bar_called?

You can find the gem here.


texts: Avoiding verbose compositional class design

texts:
I've written some code which features Eric Elliot's javascript factory function mixin composition (https://medium.com/javascript-scene/javascript-factory-functions-with-es6-4d224591a8b1), but since there's no object field name associated with the class it doesn't seem like most other forms of composition I see. What would the draw backs be compared the style of composition where each class you compose with is given a field name (I'm calling this named composition)?
let pipe = (...fns) =>x => fns.reduce((acc,fn)=> {
   return fn(acc)
 },x)
let createCanvas= ()=>o=> ({
   ...o,
   makeCanvas(width,height) {
     this.can = document.createElement("canvas")
     this.can.width = width
     this.can.height = height
     this.ctx = this.can.getContext("2d")
   },
   clearCanvas() {
     this.ctx.clearRect(0,0,this.can.width,this.can.height)
   },
   returnCanvas() {
   return this.can
 }
 })
  let drawingLines = () => o => ({
    ...o,
    line(x, y, xx, yy) {
      this.ctx.beginPath();
      this.ctx.moveTo(x, y);
      this.ctx.lineTo(xx, yy);
      this.ctx.stroke();
    }
  });
  let mouseTracker = () => o => ({
    ...o,
    trackCanvas() {
      this.track(this.can);
    },
    track(ele) {
      ele.addEventListener("mousemove", e => {
        this.bb = ele.getBoundingClientRect();
        this.mx = e.clientX - this.bb.left;
        this.my = e.clientY - this.bb.top;
      });
    }
  });
  let rectMethods = () => ({
    makeRect(x, y, w, h) {
      this.ctx.strokeRect(x, y,  w, h);
    },
  });
  let rectMixin = () => o => ({
    ...o,
    ...rectMethods()
  });

  // apparently width gets set automatically, which is pretty nice
  let height = 150;
  let width= 150;
  let firstCanvas = pipe(
    createCanvas(),
    drawingLines(),
    mouseTracker(),
    rectMixin()
  )({});

  firstCanvas.makeCanvas(width, height);
  firstCanvas.trackCanvas();

I'm very interested in avoiding the verbosity of named composition, especially in cases where an existing class has many methods that I would have to rewrite the methods for.
let usefulEventFunctions=()=>({
//...imagine functions named one-five for countings sake...
  evOne() {
},
evTwo() {
},
})
let usefulMathFunctions =()=>({
//...imagine another set of named functions one-five also...
mthOne(){
},
mthTwo(){
}
})
// here's the class composed of the others
let myObject = ()=>({
  math:usefulMathFunctions(),
  events:usefulEventFunctions(),
  // below would be the 10 signatures
evOne() {
   this.events.evOne()
},...
mthTen() {
this.math.mthTen()
}
})

Using the mixin composition I can see how we would avoid this in a language like javascript, but looking over https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance, and Object Composition, it appears other languages only feature named composition, so how is one supposed to avoid all the duplicated methods in choosing composition over inheritance?


texts: IsImageUrl extension method written in F#

texts:
I'm a newbie to F# and so I've written a small extension method library to practice the language.  The extension method attempts to determine if a url string is for an image.  I wrote the code as an extension method so that it can be used as an extension or static method in other .net languages, namely C#.

The code first checks the url's extension to see if a guess can be made about its content.  If no guess can be made, then the image is requested and the content type in the response's header is checked.

Any advice, refactorings, or criticisms welcome.
Thanks!

namespace IsImageUrlDotNet
open System.Net
open System
open System.IO

[<System.Runtime.CompilerServices.Extension>]
module IsImageUrlDotNetLib =
    let ImageFileExtensions = ["png"; "jpg"; "gif"; "raw";"bmp"; "svg"; "jpeg"; "psd";]
    let NonImageFileExtensions = ["exe"; "pdf"; "html"; "htm"; "txt"; "mp3"; "wav"; "odp";]

    let private hasAFileExtensionInList(fileExtensionList:string list) (url:string) =
      if Path.HasExtension url = false then
         false
      else
         let urlSplitList = url.ToLower().Split '.'
         let lastExtension = urlSplitList.[urlSplitList.Length - 1]
         List.contains lastExtension fileExtensionList

    let private hasAnImageFileExtension(url:string) =
      hasAFileExtensionInList ImageFileExtensions url

    let private hasAnNonImageFileExtension(url:string) =
      hasAFileExtensionInList NonImageFileExtensions url

    let private requestUrlAndCheckIfImage(url:string) =
        let req = WebRequest.Create(Uri(url))
        use resp = req.GetResponse()
        let contentType = resp.ContentType
        if contentType.Contains("text/html") then
           false
        else
            contentType.Contains("image")

    [<System.Runtime.CompilerServices.Extension>]
    let IsImageUrl(opt:string) =
      match opt with
        | null | "" -> false
        | url when Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute) = false -> false
        | url when hasAnImageFileExtension url -> true
        | url when hasAnNonImageFileExtension url -> false
        | _ -> requestUrlAndCheckIfImage opt

Sample Test (C#):

[TestMethod]
public void ShouldBeAbleToIdentifyACommonImageUrl()
{
    const string CommonImageUrl = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";

    var isImage = CommonImageUrl.IsImageUrl();

    Assert.IsTrue(isImage);
}


texts:
It was not obvious how to get a random member of a container. So I wrote a function to retrieve it given a generator.

namesapce ThorsAnvil
{
    namespace Util
    {
        using Distribution = std::uniform_int_distribution<int>;

        /* Get a distribution from [0, max)   */
        /* None maths nerds: Note the [ and ) */
        Distribution getDist(int max)
        {
            return Distribution{0, max - 1};
        }

        template<typename C, typename G>
        auto getRandomIteratorFromContainer(C& container, G& generator)
        {
            auto pos = container.begin();

            int     offset  = getDist(container.size())(generator);
            std::advance(pos, offset);

            return pos;
        }
    }
}


texts: Divide and conquer approach in search for max element

texts:
Continuing the Algorithm in a Nutshell series, here is the code:

trait MaxElem<T> {
    fn max_elem<'a>(&'a self) -> &'a T;
}

impl<T> MaxElem<T> for Vec<T> where T: PartialOrd {
    fn max_elem<'a>(&'a self) -> &'a T {
        max_elem_helper(self, 0, self.len())
    }
}

fn max_elem_helper<'a, T>(vec: &'a Vec<T>, left: usize, right: usize) -> &'a T
    where T: PartialOrd
{
    if right - left == 1 {
        return &vec[left];
    }
    let mid = (left + right) / 2;
    let max1 = max_elem_helper(vec, left, mid);
    let max2 = max_elem_helper(vec, mid, right);
    if max1 > max2 {
        max1
    } else {
        max2
    }
}

#[cfg(test)]
mod test {
    use max_elem::MaxElem;
    #[test]
    fn test_max_elem() {
        let vec = vec![11, 2, 9, 1, 3, 88];
        let m = *vec.max_elem();
        assert_eq!(m, 88);
    }
}

It's a simple algorithm that divide a vector into two parts and recursively search for the maximum.

All suggestions are welcome.


texts:
I have 16 permutations each with 104 variables using the standard alphabet. The 104 variable permutation is selected based off of compression complexity.
This is one example of the pattern I am able to generate it has a low compression ratio of 1.3 with overhead:

  HHHFHHFFHHFHHFFHHFHHHFHAAAAHHHFHHFFHHFHHFFHHFHHHFHAAAAHHHFHHFFHHFHHFFHHFHHHFHAAAAHHHFHHFFHHFHHFFHHFHHHFH

This is a goal pattern I would like to generate it has a better compression ratio of 1.5

  mlcllltlgvalvcgvpamdipqtkqdlelpklagtwhsmamatnnislmatlkaplrvhitsllptpednleivlhrwennscvekkvlgektenpkkfkinytvaneatlldtdydnflflclqdtttpiqsmmcqylarvlveddeimqgfirafrplprhlwylldlkqmeepcrf

This is one set of permutation code generation:

static double GetCompressionRatio(string input)
{
    if (string.IsNullOrEmpty(input))
        throw new ArgumentNullException();

    MemoryStream ms = new MemoryStream();

    GZipStream gzip2 = new GZipStream(ms, CompressionMode.Compress, true);

    byte[] raw = Encoding.UTF8.GetBytes(input);
    gzip2.Write(raw, 0, raw.Length);
    gzip2.Close();

    byte[] zipped = ms.ToArray(); // as a BLOB
    int startsize = raw.Length;

    double percent = Convert.ToDouble(zipped.Length) / Convert.ToDouble(startsize);
    return percent;
}

var query =
             from sp1 in polar
                    ...
                    //22 lines
                    ...
             from vp15 in polar
             where GetCompressionRatio(sp1+...+vp15)>1.5
             select sp1+...+vp15;

foreach (var element in query)
{
    //output
}
        string[] polar = new string[6];
        polar[0]="H";
        polar[1]="Q";
        polar[2]="N";
        polar[3]="K";
        polar[4]="D";
        polar[5]="E";

        string[] nonpolar = new string[5];
        nonpolar[0]="F";
        nonpolar[1]="L";
        nonpolar[2]="I";
        nonpolar[3]="M";
        nonpolar[4]="V";

        string[] all = new string[24];
        all[0]="A";
        all[1]="B";
        all[2]="C";
        all[3]="D";
        all[4]="E";
        all[5]="F";
        all[6]="G";
        all[7]="H";
        all[8]="I";
        all[9]="J";
        all[10]="K";
        all[11]="L";
        all[12]="M";
        all[13]="N";
        all[14]="O";
        all[15]="P";
        all[16]="Q";
        all[17]="R";
        all[18]="S";
        all[19]="T";
        all[20]="U";
        all[21]="V";
        all[22]="W";
        all[23]="Y";

I need it to go much faster like 1000x if possible.


texts:
For my education, I have written this basic library in Java. Maybe someone can see something that I can do better, as I'm just beginning with Java and I'm hungry to learn more.

public class Library {
    int Capacity = 10;
    int Volume = 0;
    Book[] storage = new Book[10];

    public Library() {
        System.out.println("Hello, I am a library, which can store up to 10 books!");
        this.storage = new Book[10];
    }

    public void add(Book book) {
        if (this.Volume < this.Capacity) {
            this.storage[this.Volume] = book;
            System.out.println("I added the book " + book + "!");
            this.Volume++;
        } else if (this.Volume >= this.Capacity) System.out.println("The library is full!");

    }

    public Book search(String title) {
        for (int i = 0; i < this.Volume; i++) {
            if (title.equals(this.storage[i].toString())) {
                System.out.println("The book with the title " + title + " exists in the library!");
                return this.storage[i];
            }
        }
        System.out.println("The book with the title " + title + " does not exist in the library!");
        return null;
    }

}

public class Book {
    String title;

    public Book(String title){
        this.title = title;
        System.out.println("Book " + title + " created.");}

    public String toString(){
        return this.title;
    };
}


texts: Two cross-platform implementations of getline in C

texts:
I created my cross-platform implementations of getline function in C.

It takes different arguments and have different return values than 'original' getline function, but aim is the same. The only argument input_file is file from which the line have to be read.  Return value is the line read from file or NULL if nothing read.

Here is one implementation, using fgets():

static inline char*
getline(FILE* input_file){
    const unsigned int chunk_size=256;
    char* line=malloc(chunk_size*sizeof*line+1);
    if(line==NULL){
        fprintf(stderr,"Fatal: failed to allocate %zu bytes.\n",chunk_size*sizeof*line+1);
        exit(1);
    }
    unsigned int i;
    for(i=0;;++i){
        memset(line+chunk_size*i,0,chunk_size);
        if(fgets(line+chunk_size*i,chunk_size+1,input_file)==NULL)
            break;
        if(line[strlen(line)-1]=='\n')
            break;
        char* tmp=realloc(line,chunk_size*(i+2)*sizeof*line+1);
        if(tmp==NULL){
            fprintf(stderr,"Fatal: failed to allocate %zu bytes.\n",chunk_size*(i+2)*sizeof*line+1);
            exit(1);
        }else
            line=tmp;
    }
    if(strlen(line)==0){
        free(line);
        return NULL;
    }else{
        line[strlen(line)-1]=0;
        return line;
    }
}

Here is my second implementation, using fgetc():

static inline char*
getline(FILE* input_file){
    const unsigned int chunk_size=3;
    char* line=calloc(chunk_size,sizeof*line+1);
    if(line==NULL){
        fprintf(stderr,"Fatal: failed to allocate %zu bytes.\n",chunk_size*sizeof*line+1);
        exit(1);
    }
    char c;
    unsigned int i,j;
    for(i=0,j=1;;++i){
        c=(char)fgetc(input_file);
        if(c==EOF||c=='\n')
            break;
        line[i]=c;
        if(i==chunk_size*j){
            ++j;
            char* tmp=realloc(line,chunk_size*(j+1)*sizeof*line+1);
            if(tmp==NULL){
                fprintf(stderr,"Fatal: failed to allocate %zu bytes.\n",chunk_size*(j+1)*sizeof*line+1);
                exit(1);
            }else{
                line=tmp;
                memset(line+chunk_size*j,0,chunk_size);
            }
        }
    }
    if(strlen(line)==0){
        free(line);
        return NULL;
    }else{
        line[strlen(line)]=0;
        return line;
    }
}


texts: Am I organising my PHP code effectively?

texts:
I'm very new to learning PHP & MySQL (I've got past experience with Java) and I'm doubting whether my code is organised well. I've got an index page which has two forms; the first is a form to login and the second is a form to sign up a user. So far I've only completed the signing up of a user. Please comment on my code in general and what I can improve.

The form (table tags removed):

<form action='php/signup.php' method='post' name='signup'>
    <input name='username' type='text' />
    <input name='password' type='password' />
    <input name='signin' type='submit' value='Sign up' />
</form>

signup.php:

<?php
try {
    $db = new PDO(...);
    $db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    foreach ($db->query("SELECT username FROM usertable") as $row) {
        if ($row == $username) {
            header("Location: http://example.com/#");
            return;
        }
    }
    $user = $db->prepare("INSERT INTO users (username, password) VALUES (:username, :password)");
    $user->execute(array(":username" => $_POST["username"], ":password" => $_POST["password"]));
    $db = null;
    header("Location: http://example.com/anotherpage.html");
} catch ( PDOException $e ) {
    echo $e -> getMessage();
}
?>


texts: RandomCount class: Randomising numbers in an array and generating them in a random order

texts:
public class SimpleRandomCount extends RandomCount
{
 /**
 * Generate an array containing elements in a random order
 *
 * @param size the size of the array to be generated
 */
public SimpleRandomCount(int size) {
super(size);
}

/**
* Randomise the array
*/
protected void randomise() {
int[] copy = new int[array().length];
int randomIndex;

// used to indicate if elements have been used
boolean[] used = new boolean[array().length];
Arrays.fill(used,false);
for (int index = 0; index < array().length; index++) {
    do {
        randomIndex = randomIndex();
    } while (used[randomIndex]);

    copy[index] = array()[randomIndex];
    used[randomIndex] = true;
}

for (int index = 0; index < array().length; index++) {
    array()[index] = copy[index];
   }
 }
      public static void main(String [] args){
      RandomCount count = new SimpleRandomCount(5);
      System.out.println("Array is " + Arrays.toString(count.array()));
     }
}

The SimpleRandomCount class is part of another class called RandomCount. I was wondering if there was a cleverer, shorter way of randomising the numbers without using a boolean value to help do it?

Thanks for any help it is very much appreciated.


texts: Modals that are centered vertically and horizontally within 80% of the browser size

texts:
I'm very new to website development. I would like to know if there is a much better, preferably with less codes, to write this modal.

Here is the full website assets if you need to look at how the website looks like. Just open ART.html.

function mdli(img) {
  modal = document.getElementById("modalform");
  modalimage = document.getElementById("modalimage");
  modalcentercontrol = document.getElementById("modalcentercontrol");
  modal.style.display = "block";
  modalimage.setAttribute("src", img);
  modalcentercontrol.style.marginBottom = (((-1 * (modalimage.offsetHeight / 2)) + 5) + "px");
}

function modalclose() {
  modal = document.getElementById("modalform");
  modal.style.display = "none";
}
div.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 89%;
  height: 100%;
  overflow: hidden;
  background-color: #000000;
}
div.modalimage {
  height: 100%;
  width: 90%;
  margin: 0 auto 0 auto;
}
div.modalcentercont {
  width: 100%;
  height: 50%;
  margin: 0 0 50% 0;
}
img.art:hover {
  opacity: 0.5;
}

  <title>Heath Aleksandr</title>
  <link rel="stylesheet" href="CSS.css" />
  <link rel="icon" href="ICON_32.png">


texts: Import "izip" for different versions of Python

texts:
A common idiom that I use for Python2-Python3 compatibility is:

try:
    from itertools import izip
except ImportError:  #python3.x
    izip = zip

However, a comment on one of my Stack Overflow answers implies that there may be a better way.  Is there a more clean way to accomplish this?