texts:
I have a lookup table "RequestTypes" that has the following data:

ID      Type
----   -----

1      Leave
2      Loan
3      BlahBlah

Using EF, and whenever the need arise to check the type of the request, I used to do something like:

if (row.RequestType.ID == 1)
{
     // request is leave
}
else if (row.RequestType.ID == 2)
{
    // request is loan
}
//......

As you can see, there are lots of magic numbers. Anyway, I then created an enum that matches the lookup values:

public enum RequestTypesEumn
{
     Leave = 1,
     Loan = 2,
     BlahBlah = 3
}

and when I need to check the request type, I do something like:

if ((RequestTypesEumn)row.RequestType.ID == RequestTypesEumn.Leave)
{
     // request is leave
}
else if ((RequestTypesEumn)row.RequestType.ID == RequestTypesEumn.Loan)
{
    // request is loan
}
//......

That's a little bit better, except it is a lot of casting. So I created a partial class of the Request object and overloaded the == and != operators to match it against the automatically generated virtual property RequestType:

public static bool operator ==(RequestType type, RequestTypesEumn typeEnum)
{
    if (type== null)
       return false;

    return (type.ID == (int)typeEnum);
}

public static bool operator !=(RequestType type, RequestTypesEumn typeEnum)
{
    if (type== null)
       return true;

    return (type.ID != (int)typeEnum);
}

So now I can simply do:

if (row.RequestType == RequestTypesEumn.Leave)
{
     // request is leave
}
else if (row.RequestType == RequestTypesEumn.Loan)
{
    // request is loan
}
//......

Let alone inline code in ASP.NET as in repeaters and grids, for example to change the row color depending on the type we'll need to check the type and so on.

Is that a good practice? is it the best possible way to deal with enums especially when the logic requires a lot of matching as in my case?


texts:
The problem to the question is:

  Write a program that takes 3 integers as an input from the user using input dialog messages and sorts the three numbers.

I just want to know: is there any major differences between my code and the book's code in terms of efficiency or anything specific that I could have done better in my code? I am slowly learning Java and am trying to pick up the best techniques as I go along trying to learn this language. Also, I really don't understand the logic behind the book's answer. It seems as if they are only comparing two numbers, but how can they guess what the third number will be in the sort?

Note: I am following my textbook and the newest thing we have learned are if and else statements along with switch statements. I have not learned any looping and I am still in the basics. I am following Introduction To Java Programming 9th edition Daniel Liang and this is from the Chapter 3 exercises.

My solution:

package Chapter3Exercises;
import javax.swing.JOptionPane;

public class SortThreeIntegers
{
    public static void main(String[] args)
    {
        //Prompt user to enter three integers

        String stringNum1 = JOptionPane.showInputDialog(null, "Please enter 1st Integer: ");
        String stringNum2 = JOptionPane.showInputDialog(null, "Please enter 2nd Integer: ");
        String stringNum3 = JOptionPane.showInputDialog(null, "Please enter 3rd Integer: ");

        int num1 = Integer.parseInt(stringNum1);
        int num2 = Integer.parseInt(stringNum2);
        int num3 = Integer.parseInt(stringNum3);

        if ((num1 > num2 && num1 > num3))
        {
            if(num2 > num3)
            {
                System.out.print(num3 + " " + num2 + " " + num1);
            }
            else
                System.out.print(num2 + " " + num3 + " " + num1);
        }
        else if ((num2 > num1 && num2 > num3))
        {
            if(num1 > num3)
            {
                System.out.print(num3 + " " + num1 + " " + num1);
            }
            else
                {
                System.out.print(num1 + " " + num3 + " " + num2);
                }
        }
        else if ((num3 > num1 && num3 > num2))
        {
            if(num1 > num2)
            {
                System.out.print(num2 + " " + num1 + " " + num3);
            }
            else
                System.out.print(num1 + " " + num2 + " " + num3);
        }
        else
        {
            System.out.println("ERROR!");
        }

    }

}

Book's solution:

public class Exercise03_08 {
  public static void main(String[] args) {
    java.util.Scanner input = new java.util.Scanner(System.in);

    // Enter three numbers
    System.out.print("Enter three integers: ");
    int number1 = input.nextInt();
    int number2 = input.nextInt();
    int number3 = input.nextInt();

    if (number1 > number2) {
      int temp = number1;
      number1 = number2;
      number2 = temp;
    }

    if (number2 > number3) {
      int temp = number2;
      number2 = number3;
      number3 = temp;
    }

    if (number1 > number2) {
      int temp = number1;
      number1 = number2;
      number2 = temp;
    }

    System.out.println("The sorted numbers are "
      + number1 + " " + number2 + " " + number3);
  }
}


texts:
I have a series of four method calls that all return Try[Something], with the last returning Try[Unit]. Something like this:

def getFields(): Try[List[A]] = { ... }
def getValues(): Try[List[B]] = { ... }
def createTmpFile(as: List[A], bs: List[B]): Try[C] { ... }
def runProcessWithFile(c: C): Try[Unit] { ... }

def run(): Try[Unit] = {
  for (
    fields <- getFields();
    values <- getValues();
    file <- createTmpFile(fields, values);
    _ <- runProcessWithFile(file)
  ) yield ()
}

This seems OK to me. I guess my first question is about Try[Unit]. That seems a little awkward. Option[Exception] seems equally awkward. Is there a "best practice" return type in Scala for a possible Exception?

Also, things got complicated when I wanted to add branching based on whether getValues() returns an empty list. This is what I have right now:

def run(): Try[Unit] = {
  for (
    fields <- getFields();
    values <- getValues();
    _ <- if (values.nonEmpty) {
      for (
        file <- createTmpFile(fields, values);
        _ <- runProcessWithFile(file)
      ) yield ()
    } else {
      Success(())
    }
  ) yield ()
}

That seems pretty hairy. Is there a better way to do this? I suppose I could abandon Try altogether and just let everything throw Exceptions, but that seems like throwing the baby out with the bathwater.


texts: JavaScript: implement event listener in custom object

texts:
For many years, there have been several JavaScript libraries for implementing custom events and event listeners. But, as MDN web docs suggests, there are now available constructable Event, CustomEvent and EventTarget objects. So, what would now be the standard approach to equip my custom class with event-emitting qualities?

This is the ES6 code I am using now, it works fine.

class MyObject extends EventTarget {
  constructor(name) {
    super();
    this.name = name;
  }
  trigger(message) {
    const e = new CustomEvent('update', {detail: {message}});
    this.dispatchEvent(e);
  }
}

const o = new MyObject('Good Boy');

o.addEventListener('update', e => {
  console.log('Update event by', e.target.name, 'triggered, message:', e.detail.message);
});

// Should output to the console: Update event by Good Boy triggered, message: Hello
o.trigger('Hello');

Are there any risks with this approach? Other than that it would not work on certain older browser versions. I have some reservations about the fact that I have to inherit from the EventTarget class. If the MyObject class would inherit from some parent class, and I'd want to equip with event emitter only the child class, it appears there would be no clean way to do that.

Here's my lousy attempt to mix in the EventTarget methods so that there's no need to inherit from the EventTarget class:

class MyObject {
  constructor(name) {
    this.name = name;
    this.eventEmitter = new EventTarget();
    this.addEventListener = (...args) => this.eventEmitter.addEventListener(...args);
    this.removeEventListener = (...args) => this.eventEmitter.removeEventListener(...args);
    this.dispatchEvent = (...args) => this.eventEmitter.dispatchEvent(...args);
  }
  trigger(message) {
    const e = new CustomEvent('update', {detail: {emitter:this, message}});
    this.dispatchEvent(e);
  }
}

const o = new MyObject('Good Boy');

o.addEventListener('update', e => {
  console.log('Update event by', e.detail.emitter.name, 'triggered, message:', e.detail.message);
});

o.trigger('Hello');

The ugly thing here is that now e.target does not point to MyObject instance but rather to its eventEmitter property. I am forced to pass it via the event details, it's not pretty but this kind of works.


texts:
Each product in my e-commerce website has Arabic and English values for the title, description and excerpt. I have this method EditProduct to update those values based on current culture (Arabic or English)

public void EditProduct(string element, string text1, string text2, bool edit1, bool edit2, string culture)
{
    var product = DoSomeMagicToGetAProduct();

    if (element == "title")
    {
        if (culture == "en")
        {
            if (edit1)
            {
                product.Title = text1;
            }
            if (edit2)
            {
                product.TitleAr = text2;
            }
        }

        if (culture == "ar")
        {
            if (edit1)
            {
                product.TitleAr = text1;
            }
            if (edit2)
            {
                product.Title = text2;
            }
        }
    }

    if (element == "description")
    {
        // similar codes here
    }

    if (element == "excerpt")
    {
        // similar codes here
    }

    product.Save();

}

The method works well, but I think I can improve the way I write it to be more elegant.
Any suggestions?


texts:
I have created what was a rather simple piece of code to calculate the factorial of a number, although I wanted to ensure that my program could calculate the factorial of any given number. To do this, the only data type I thought was relevant was BigInteger. The problem I had with this was that my code quickly became quite messy, nevertheless, it works! I have chosen to take the approach of using recursion to calculate the answer, as I felt it is the best way to keep the code short and efficient.

I have looked at others code on this site, and read the reviews given, and it seems most users have chosen to use int, which isn't a problem, although as I say, I don't want an IntegerOverflow to occur when the user gives their input.

Is there a way to "clean up" this code; or make it more efficient?

import java.math.BigInteger;
public class Factorial {
    public static void main (String [] args) {
        java.util.Scanner sc = new java.util.Scanner(System.in);
        System.out.print("Enter an integer to calculate the factorial of: ");
        BigInteger temp = sc.nextBigInteger();
        sc.close();
        System.out.println(temp + "! = " + calculateFactorial(temp));
    }

    private static BigInteger calculateFactorial (BigInteger n) {
        if (n.compareTo((new BigInteger("1"))) ==  -1) {
            return new BigInteger("1");
        } else {
            return (n.multiply(calculateFactorial(n.subtract(new BigInteger("1")))));
        }
    }
}


texts: Finding the number in a list that differs in parity

texts:
Given any string with a series of numbers find out which one of the numbers differs from the others in evenness and return its position.

Examples:

"2 4 6 7 8 10" returns 4
"3 5 7 9 10" returns 5

I found 2 different ways to do so, but I'm wondering what is the best approach in matter of time complexity.

Solution 1

def num_test(numbers)
  (i = numbers.split.map(&:to_i)).index(i.partition(&:odd?).find(&:one?).first)+1
end

Solution 2

def num_test(numbers)
  numbers.index(numbers.split.map(&:to_i).partition(&:odd?).find(&:one?).first.to_s)+1
end

Also, any other solution is welcome.


texts:
I have a heading, which is an integer and from it I would like to figure out the compass direction (North, North-East,...) and return the appropriate icon. I feel like I'm probably already at the cleanest solution but I would love to be proven wrong.

public GetHeadingImage(string iconName, int heading){
        if (IsNorthHeading(heading))
            return iconName  + "n" + ICON_FILE_EXTENTION;
        if (IsNorthEastHeading(heading))
            return iconName + "ne" + ICON_FILE_EXTENTION;
        if (IsEastHeading(heading))
            return iconName + "e" + ICON_FILE_EXTENTION;
        /*A bunch more lines*/
}
private bool IsNorthHeading(int heading)
{
    return heading < 23 || heading > 337;
}
/* A bunch more extracted test methods*/


texts: Max function with variable number of arguments

texts:
I find it irritating that in standard C++ I can't do std::max(a, b) = x when it's possible and that it can't handle more than 2 arguments. For the second concern I found this std::min tutorial and it looks interesting but the usage of pointers confuses me because I don't understand why they are needed here. Since I want to learn more about c++ I wanted to try to create my own version of std::max while making use of the latest c++ features that I know of.

First I want to make use of concepts to let the user know when the types of arguments are invalid at compilation time:

namespace std1 {

// Helper concept for static_assert
template<typename>
concept False = false;

template<typename T>
concept Boolean = std::is_same_v<T, bool>;

template<typename T>
concept TypeLessThanComparable = requires(T a, T b) {
    { a < b } -> Boolean;
};

template<typename T>
concept TypeLessThanEqComparable = requires(T a, T b) {
    { a <= b } -> Boolean;
};

template<typename T>
concept TypeGreaterThanComparable = requires(T a, T b) {
    { a > b } -> Boolean;
};

template<typename T>
concept TypeGreaterThanEqComparable = requires(T a, T b) {
    { a >= b } -> Boolean;
};

These are the functions themselves:

template<typename T>
constexpr decltype(auto) max(T&& a) noexcept
{
    return std::forward<T>(a);
}

template<typename T>
constexpr decltype(auto) max(T&& a, T&& b) noexcept
{
    if constexpr(TypeLessThanComparable<T>) {
        return a < b ? std::forward<T>(b) : std::forward<T>(a);
    }
    else if constexpr(TypeLessThanEqComparable<T>) {
        return a <= b ? std::forward<T>(b) : std::forward<T>(a);
    }
    else if constexpr(TypeGreaterThanComparable<T>){
        return a > b ? std::forward<T>(a) : std::forward<T>(b);
    }
    else if constexpr(TypeGreaterThanEqComparable<T>) {
        return a >= b ? std::forward<T>(a) : std::forward<T>(b);
    }
    else {
        // if I just put false in static_assert it gives a compilation error no matter what
        static_assert(False<void>, "You called max with invalid arguments, cannot find comparison operators for their type");
    }
}

template<typename T, typename...Ts>
constexpr decltype(auto) max(T&& a, T&& b, T&& c, Ts&&...d) noexcept
{
    return max(a, max(b, max(c, d...)));
}

} // namespace std1

And some tests:

struct A{};

struct B
{
    bool operator<(B const&) const noexcept = delete;
    bool operator<=(B const&) const noexcept = delete;
    bool operator>(B const&) const noexcept = delete;
    bool operator>=(B const&) const noexcept;
};

int main()
{
    static_assert(std1::max(1, 2) == 2);

    int a = 1;
    int b = 5;
    int c = 3;
    int d = 2;

    assert(std1::max(a, b, c, d) == b);

    std1::max(b, c, d) = 4;

    assert(b == 4);

    // This gives a compilation error because the static assertion failed
    // (void)std1::max(A{}, A{});

    // This works
    std1::max(B{}, B{}, B{}, B{}, B{});
}

I want to know if the code is well written and could replace std::max in c++20, maybe it has bugs that I'm not aware of since I am inexperienced in c++. You could also check the compiler explorer link: https://godbolt.org/z/5urgqR.


texts: Removeclass addclass multiple selectors optimization

texts:
I've written a function that works fine, but being new to jQuery, I'd like some reviews on writing this more cleanly. Anything advice would help; just trying to learn!

function displayContent() {
  var $link1 = $('.row.nav li a.bio');
  var $link2 = $('.row.nav li a.stylist');
  var $link3 = $('.row.nav li a.contact');
  var $content = $('#text-content')
  var $bio = $("#bio");
  var $stylist = $("#stylist");
  var $contact = $("#contact");
  var $overlay = $('.content-overlay');

  //link1
  $link1.click(function (e) {
    e.stopPropagation();
    $link2.removeClass('active');
    $link3.removeClass('active');
    $link1.addClass('active');
    $contact.hide();
    $stylist.hide();
    $bio.fadeIn(700);
    $overlay.show();
  });
  //link2
  $link2.click(function (e) {
   //same code here
  });
  //link3
  $link3.click(function (e) {
    //same code here
  });

  //close overlay/hide content
  $('html').click(function (e) {
//hide code
  });

}


texts: Design To Handle Multiple Similar Model Class

texts:
I am doing a web app for an event company whereby customer can access the website for a self-help instant quotation. Customer will choose the type of event, fill a form and expect an instant quotation.

Can anyone give me some tips how can I improve my design? Below are my current design thoughts.

Quotation class:

public class Quotation{

    // Customer specific details
    private String customerName;
    private String customerEmail;
    private String customerMobile;

    // Event specific details
    private WeddingEvent weddingEvent;
    private RetreatEvent retreatEvent;
    // ... another 4 or 5 more event classes

    // getters and setters
    // ...
}

Event Classes:

public class BaseEvent{
    private int attendance;
    private String venue;
}

public class WeddingEvent extends BaseEvent{
    private boolean needWeddingPlanner;
    // getters and setters
    // ...
}

public class RetreatEvent extends BaseEvent{
    private boolean needBreakfast;
    private boolean needLunch;
    private boolean needDinner;

    // getters and setters
    // ...
}


texts:
Does anybody have an idea on how to make this code more idiomatic? I tried to use scalaz Traverse, but it didn't really help.

Given the types and method signatures:

  type HTTPResult = Future[Either[Throwable, String]]
  type FeedResult = Either[Throwable, Feed]

  def fetchHtml(item: FeedItem): HTTPResult

  def fetchFeed(feedUrl: String): HTTPResult

Feed and FeedItem are case classes.

I am looking for a way to simplify this function:

  def fetchAll(feedUrl: String): FeedResult = {
    val feed = fetchFeed(feedUrl).apply().right.flatMap(Feed.fromXml).right

    val scoredItems = feed.map {
      _.items.par.map { feedItem ⇒
        fetchHtml(feedItem).apply().right.map { feedHtml ⇒
          feedItem.copy(score = Feed.findScore(feedHtml))
        }
      }.foldLeft(List[FeedItem]())((acc, itemE) ⇒
        itemE match {
          case Left(t) ⇒
            logger.error("Could not download item score: ", t)
            acc
          case Right(v) ⇒ v :: acc
        })
    }

    scoredItems.right.flatMap(l ⇒ feed.map(_.copy(items = l)))
  }

I tried using for, but I am using mostly map, not flatMap and the types are different, so I can't really use for for everything and would get a weird mixture.

Any idea?


texts: Function to get top k words in a given String

texts:
This is a two-part job:

to identify a word
to find the top k words

I've tried to use regex to split but it's taking 10x more time when string is really long. The top k strings are found using a priority queue. I've created a min priority queue for first k element, if the frequency of the next word is greater than the min element. I then remove min and insert the new word.

 public static List<String> getTopStrings(String input, int k)
        {
            if(k<0)
                throw new IllegalArgumentException("Value k cannot be negative for top k elements: k= "+k);
            List<String> list = new ArrayList<String>();
            if(input==null || input.isEmpty() || k==0)
            {
                return list;
            }
            Set<Character> separators = new HashSet<Character>();
            separators.add(' ');
            separators.add(',');
            separators.add('.');
            separators.add(';');
            separators.add(':');
            separators.add('"');
            separators.add('(');
            separators.add(')');
            separators.add('-');
            separators.add('/');
            separators.add('\\');
            separators.add('\'');
            separators.add('?');
            separators.add('\n');
            separators.add('\r');
            separators.add('!');
            separators.add('|');
            separators.add('~');
            separators.add('\'');
            separators.add('[');
            separators.add(']');
            separators.add('{');
            separators.add('}');
            separators.add('&');
            separators.add('%');
            separators.add('$');
            separators.add('#');
            separators.add('@');
            separators.add('*');
            separators.add('=');
            separators.add('+');
            separators.add('>');
            separators.add('<');

            final Map<String, Integer> wordMap = new HashMap<String, Integer>();
            int count, wordStart=0;
            for(int i=0;i<input.length();i++)
            {
                if(separators.contains(input.charAt(i)))
                {
                    addWord(input, wordMap,wordStart,i);
                    wordStart=i+1;
                }
            }
            addWord(input,wordMap,wordStart,input.length());
            List<String> keySet = new ArrayList<String>();
            keySet.addAll(wordMap.keySet());
            if(keySet.size()<=k){
                return keySet;
            }

            PriorityQueue<String> minHeap = new PriorityQueue<String>(k, new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    return (wordMap.get(o1)-wordMap.get(o2));
                }
            });

            for(int i=0;i<k;i++)
            {
                minHeap.add(keySet.get(i));
            }
            for(int i=k;i<keySet.size();i++)
            {
                String key = keySet.get(i);
                count = wordMap.get(key);
                if(count>wordMap.get(minHeap.peek()))
                {
                    minHeap.poll();
                    minHeap.add(key);
                }
            }
            list.addAll(minHeap);
            return list;
        }
        public static void addWord(String input, Map<String, Integer> wordMap, int startIndex, int endIndex)
        {
            int count = 0;
            String word = input.substring(startIndex, endIndex).toLowerCase();
            if(word!=null && !word.isEmpty())
            {
                if(wordMap.containsKey(word))
                {
                    count = wordMap.get(word);
                }
                wordMap.put(word, count+1);
            }
        }


texts: Spring Boot methods to add and remove relationships

texts:
I have a Spring Boot application and I wrote a piece of code to manage relationships between two entities.

The code consists mostly in these two methods:

@Override
    public void associateDocumentsToPersonRecord(Long personRecordId, AssociationDTO associationDTO) {
        PersonRecord personRecord = personRecordRepository.findById(personRecordId).orElse(null);
        if (personRecord == null)
            return;

        for (Long documentId : associationDTO.getDocumentsId())
            documentRepository
                    .findById(documentId)
                    .ifPresent(document -> personRecord.getDocuments().add(document));

        personRecordRepository.save(personRecord);
    }

    @Override
    public void removeAssociateDocumentsToPersonRecord(Long personRecordId, AssociationDTO associationDTO) {
        PersonRecord personRecord = personRecordRepository.findById(personRecordId).orElse(null);
        if (personRecord == null)
            return;

        for (Long documentId : associationDTO.getDocumentsId())
            documentRepository
                    .findById(documentId)
                    .ifPresent(document -> personRecord.getDocuments().remove(document));

        personRecordRepository.save(personRecord);
    }

One method is for adding relations, the other is to remove them.

I definitely get the smell of duplicated code and the only thing that changes is remove or add between the two methods.
How could I refactor this code in the most elegant way?


texts:
I'm trying to implement a version of the 3SUM problem. Any help with code style and efficiency would be greatly appreciated. I'm trying to get it roughly \$O(n^2)\$. Also, there should be no duplicates. I specifically wanted to try and build upon 2SUM. I know there are other, maybe better, ways to do it.

def two_sum(nums, target):
    d = {}
    for i in range(len(nums)):
        key = target - nums[i]
        if key in d:
            return [nums[d[key]], nums[i]]
        else:
            d[nums[i]] = i
    return []

def three_sum(nums):
    ans = set()
    for n in nums:
        lst = two_sum(nums, -n)
        if lst:
            lst.append(n)
            ans.add(tuple(sorted(lst)))
    return ans

print(three_sum(nums))


texts:
I have this 2 arrays :

final int[] tabSelected = {
        R.drawable.iconWhite0,
        R.drawable.iconWhite1,
        R.drawable.iconWhite2,
        R.drawable.iconWhite3,
        R.drawable.iconWhite4};
final int[] tabsUnselected = {
        R.drawable.iconBlack0,
        R.drawable.iconBlack1,
        R.drawable.iconBlack2,
        R.drawable.iconBlack3,
        R.drawable.iconBlack4};

I just don't understand how I can simplify this, by making a for loop ..although I am sure it is very easy, I just don't see it.

  @Override
        public void onPageSelected(int position) {
            switch (position) {
                case 0:
                    tabLayout.getTabAt(0).setIcon(tabSelected[0]);
                    tabLayout.getTabAt(1).setIcon(tabsUnselected[1]);
                    tabLayout.getTabAt(2).setIcon(tabsUnselected[2]);
                    tabLayout.getTabAt(3).setIcon(tabsUnselected[3]);
                    tabLayout.getTabAt(4).setIcon(tabsUnselected[4]);
                    break;

                case 1:
                    tabLayout.getTabAt(0).setIcon(tabsUnselected[0]);
                    tabLayout.getTabAt(1).setIcon(tabSelected[1]);
                    tabLayout.getTabAt(2).setIcon(tabsUnselected[2]);
                    tabLayout.getTabAt(3).setIcon(tabsUnselected[3]);
                    tabLayout.getTabAt(4).setIcon(tabsUnselected[4]);
                    break;

                case 2:
                    tabLayout.getTabAt(0).setIcon(tabsUnselected[0]);
                    tabLayout.getTabAt(1).setIcon(tabsUnselected[1]);
                    tabLayout.getTabAt(2).setIcon(tabSelected[2]);
                    tabLayout.getTabAt(3).setIcon(tabsUnselected[3]);
                    tabLayout.getTabAt(4).setIcon(tabsUnselected[4]);
                    break;

                case 3:
                    tabLayout.getTabAt(0).setIcon(tabsUnselected[0]);
                    tabLayout.getTabAt(1).setIcon(tabsUnselected[1]);
                    tabLayout.getTabAt(2).setIcon(tabsUnselected[2]);
                    tabLayout.getTabAt(3).setIcon(tabSelected[3]);
                    tabLayout.getTabAt(4).setIcon(tabsUnselected[4]);
                    break;

                default:
                    tabLayout.getTabAt(0).setIcon(tabsUnselected[0]);
                    tabLayout.getTabAt(1).setIcon(tabsUnselected[1]);
                    tabLayout.getTabAt(2).setIcon(tabsUnselected[2]);
                    tabLayout.getTabAt(3).setIcon(tabsUnselected[3]);
                    tabLayout.getTabAt(4).setIcon(tabSelected[4]);
                    break;
            }
        }


texts: Move zipped files from multiple subfolders into one master folder via loop process

texts:
I am trying to write a code that:

First Prompt: asks the user to select the folder that contains all zipped folders where each zipped folder contains a data file.

Second Prompt: Ask the user to select the master folder path to place the unzipped data files into.

The program will unzip the first zipped folder, copy the data file out, paste the data file into the designated master folder the user was prompted to select from their second prompt.

The program will find the next zipped folder, unzip and open the folder, copy out the file it contains, paste the file into the master folder, rinse and repeat until all the files from each of the zipped folders are moved over.

I am trying to make a folder that contains all the zipped data files in order to concatenate all the data into a master document. Then I will be able to run an analysis on this data.

This code works but I need some help with getting the code to run faster.  I tested the program on a folder that contained only 6 zipped files and it moved the files over in 2 seconds.  But now I'm testing the program on a folder that contains 8020 zipped files and its moving over the files at a rate of 1 file every 8 seconds.

I have "Microsoft Shell Controls And Automation", "Visual Basic For Applications", "Microsoft Excel 15.0 Object Library", OLE Automation", "Microsoft Office 15.0 Object Library", Microsoft Forms 2.0 Objection Library" options enabled.

Can anyone help me speed this up?

Option Explicit

Sub UnzipFileMoveToMasterFolder()

Dim oApp As Shell
Dim strFile As String
Dim FolderPath As FileDialog
Dim MasterFolder As String
Dim ZipFolder As String
Dim i As Integer

'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False

'Retrieve target master workbook data folder path from user
Set FolderPath = Application.FileDialog(msoFileDialogFolderPicker)

With FolderPath
  .Title = "Select a master folder location to store the unzipped files."
  .AllowMultiSelect = False
    If .Show <> -1 Then GoTo CancelSelect1
    MasterFolder = .SelectedItems(1) & "\"
End With

'In case Cancel selected
CancelSelect1:
MasterFolder = MasterFolder
If MasterFolder = "" Then GoTo ResetSettings

'Retrieve target data folder path from user
Set FolderPath = Application.FileDialog(msoFileDialogFolderPicker)

With FolderPath
  .Title = "Select folder location that contains the zipped folders with desired data files."
  .AllowMultiSelect = False
    If .Show <> -1 Then GoTo CancelSelect2
      ZipFolder = .SelectedItems(1) & "\"
End With

'In case Cancel selected
CancelSelect2:
ZipFolder = ZipFolder
If ZipFolder = "" Then GoTo ResetSettings

'get a shell object
Set oApp = CreateObject("Shell.Application")
'get all the files in the directory that are zip files

strFile = Dir(ZipFolder & "*.zip")
'loop until we cannot find anymore files
Do While strFile <> ""
        'check to see if the zip contains items
        If oApp.Namespace(ZipFolder).Items.Count > 0 Then
            'loop through all the items in teh zip file
            For i = 0 To oApp.Namespace(ZipFolder).Items.Count - 1
            'save the files to the new location
            oApp.Namespace(MasterFolder).CopyHere oApp.Namespace(ZipFolder & strFile).Items.Item(i)
            Next i
        End If
    'get the next file in the directory
    strFile = Dir
Loop
'free memory
Set oApp = Nothing

'Reset Macro Optimization Settings
ResetSettings:
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True

'Message Box when tasks are completed
MsgBox "Task Complete!"
Application.Cursor = xlDefault

End Sub


texts: Build a Person class, delegate don't duplicate

texts:
I am currently learning javascript and I attempted to make a Person class (note - this was part of a practice exercise, so some of the design decisions may have been due to the requirements).

Specifically, I am looking for feedback on:

Usage of prototypes (i.e. from my understanding, prototype should be used when the particular behaviour/property is shared with all objects. This means there is only 1 instance of the function (e.g.) getFullName() which is shared across all objects, whereas the properties fullName, firstName and lastName which are declared directly in the Person function, thus a new unique copy will be created in every instance.
Usage of undefined (i.e. exercise required us to initially have obj.firstName to be equal to undefined. But does it make more sense to have these properties equal to undefined, or to have it equal to null, or to equal an empty string (like "").
Usage of this (am I generally correct in the usage of this? Particularly when prototypes are used)

var Person = function(firstAndLast) {
    this.fullName = firstAndLast;
    this.firstName = undefined;
    this.lastName = undefined;
};

Person.prototype.setFullName = function(firstAndLast){
    this.fullName = firstAndLast;
};
Person.prototype.setFirstName = function(first){
    this.firstName = first;
};
Person.prototype.setLastName = function(last){
    this.lastName = last;
};
Person.prototype.getFullName = function(){
    return this.fullName;
};
Person.prototype.getFirstName = function(){
    //exercise required a default firstName to be set, only if this function was called
    if(this.firstName === undefined){
        this.firstName = this.defaultFirst();
    }
    return this.firstName;
};
Person.prototype.getLastName = function(){
    //exercise required a default lastName to be set, only if this function was called
    if(this.lastName === undefined){
        this.lastName = this.defaultLast();
    }
    return this.lastName;
};

Person.prototype.defaultFirst = function(){
    var first = "";
    for(var i=0;i<this.fullName.length; i++){
        if(this.fullName[i] !== " "){
            first += this.fullName[i];
        }else{
            break;
        }
     }
    return first;
};

Person.prototype.defaultLast = function(){
    var last = "";
    for(var i=this.fullName.length-1; i>0; i--){
        if(this.fullName[i] !== " "){
            last += this.fullName[i];
        }else{
            break;
        }
    }
    return last.split("").reverse().join("");
};


texts:
Three days ago I wrote about a Java Dice Roller I wrote. I've now added a GUI to that program. Here it is:

DiceRollerGUI.java:

package com.egroegnosbig.dicerollergui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class DiceRollerGUI {
    static JFrame frameOne = new JFrame("Dice Roller");
    public static void main(String[] args) {
        frameOne.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        DiceGUI GUI = new DiceGUI();
        frameOne.add(GUI);

        Button b = new Button("Roll");
        b.addActionListener(new ButtonAction());
        frameOne.add(b);
        frameOne.setLayout(new GridLayout(1, 2));
        frameOne.setSize(400, 250);
        frameOne.setResizable(false);
        frameOne.setVisible(true);
    }
}

class ButtonAction implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        DiceRollerGUI.frameOne.setVisible(false);
        JFrame frameTwo = new JFrame("Dice Roller");
        frameTwo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frameTwo.setSize(400, 250);
        frameTwo.setResizable(false);
        ResultGUI resultGUI = new ResultGUI();
        frameTwo.add(resultGUI);
        frameTwo.setVisible(true);
    }
}

DiceGUI.java:

package com.egroegnosbig.dicerollergui;

import java.awt.*;
import javax.swing.*;

public class DiceGUI extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        this.setBackground(Color.WHITE);

        g.drawString("Dice Roller", 70, 20);
    }
}

ResultGUI.java:

package com.egroegnosbig.dicerollergui;

import java.awt.*;
import javax.swing.*;

public class ResultGUI extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        this.setBackground(Color.WHITE);

        Dice dice = new Dice(6);
        int resultInt = dice.roll();
        StringBuilder sb = new StringBuilder();
        sb.append("");
        sb.append(resultInt);
        String result = sb.toString();
        g.drawString("The dice rolled a", 150, 125);
        g.drawString(result, 243, 125);
    }
}

Dice.java:

package com.egroegnosbig.dicerollergui;

import java.util.Random;

public class Dice {
    private final Random rand;
    private final int faces;

    public Dice(int faces) {
        this.rand = new Random();
        this.faces = faces;
    }

    public int roll() {
        return rand.nextInt(faces) + 1;
    }
}

Working on better class names...


texts: Finding the total time elapsed in the union of time intervals

texts:
Given a set of time intervals, I have to find the total time elapsed in the union of the intervals.

Test Cases:

int[][] test = {{10, 14}, {4, 18}, {19, 20}, {19, 20}, {13, 20}};
int[][] test2 = {{1, 3}, {3, 6}};
answer(test) == 16
answer(test2) == 5

Both of the tests pass, but I get a "time limit exceeded". How can I get this function to run faster?

Here's my answer function:

public static int answer(int[][] intervals) {
    ArrayList<Integer> t = new ArrayList<Integer>();
    for (int i = 0; i < intervals.length; i++) {
        for (int j = intervals[i][0]; j < intervals[i][1]; j++) {
            if (!t.contains(j))
                t.add(j);
        }
    }
    return t.size();
}

I also made an attempt without using the ArrayList and instead a regular array (int[]):

public static boolean wasWatched(int[] array, int time) {
    for (int i = 0; i < array.length; i++) {
        if (array[i] == time)
            return true;
    }
    return false;
}
public static int[] addTimeWatched(int[] array, int time) {
    int[] temp = new int[array.length + 1];
    for (int i = 0; i < array.length; i++) {
        temp[i] = array[i];
    }
    temp[array.length] = time;
    return temp;
}

The answer() function was the same except t was an int[] and it used wasWatched(t, j) instead of t.contains(j) as well as t = addTimeWatched(t, j) instead of t.add(j).

Here is the full challenge text:

Zombit monitoring

The first successfully created zombit specimen, Dolly the Zombit, needs constant monitoring, and Professor Boolean has tasked the minions with it. Any minion who monitors the zombit records the start and end times of their shifts. However, those minions, they are a bit disorganized: there may be times when multiple minions are monitoring the zombit, and times when there are none!

That's fine, Professor Boolean thinks, one can always hire more minions... Besides, Professor Boolean can at least figure out the total amount of time that Dolly the Zombit was monitored. He has entrusted you, another one of his trusty minions, to do just that. Are you up to the task?

Write a function answer(intervals) that takes a list of pairs [start, end] and returns the total amount of time that Dolly the Zombit was monitored by at least one minion. Each [start, end] pair represents the times when a minion started and finished monitoring the zombit. All values will be positive integers no greater than 2^30 - 1. You will always have end > start for each interval.

Test cases

Inputs:
    (int) intervals = [[1, 3], [3, 6]]
Output:
    (int) 5

Inputs:
    (int) intervals = [[10, 14], [4, 18], [19, 20], [19, 20], [13, 20]]
Output:
    (int) 16

Contraints

Your code will be compiled using standard Java 7. It must implement the answer() method in the solution stub.

Execution time is limited. Some classes are restricted (e.g. java.lang.ClassLoader). You will see a notice if you use a restricted class when you verify your solution.

Third-party libraries, input/output operations, spawning threads or processes and changes to the execution environment are not allowed.


texts:
Logical processors available on my machine:

CPU(s):              4
Thread(s) per core:  2

So, 2x4 = 8 logical processors. But am currently using only 4 go-routines that should map to 4 OS threads.

$ lscpu
Architecture:        x86_64
CPU op-mode(s):      32-bit, 64-bit
Byte Order:          Little Endian
CPU(s):              4
On-line CPU(s) list: 0-3
Thread(s) per core:  2

Each go routine is given 2K stack. GoLang by design does not have stackoverflow issues for medium size data, because it grows the stack size, until a limit

So, am using recursive approach instead of an efficient iterative approach

Divided the input into 4 parts instead of 8 parts.

package expressions

import (
    "fmt"
    "sync"
)

func FindMax(list []int, length int) int {

    var wg sync.WaitGroup
    wg.Add(1)
    var max1 int
    go func() {
        max1 = max(list[0 : length/4])
        wg.Done()
    }()
    wg.Add(1)
    var max2 int
    go func() {
        max2 = max(list[length/4 : length/2])
        wg.Done()
    }()
    wg.Add(1)
    var max3 int
    go func() {
        max3 = max(list[length/2 : 3*length/4])
        wg.Done()
    }()
    wg.Add(1)
    var max4 int
    go func() {
        max4 = max(list[3*length/4 : length])
        wg.Done()
    }()

    wg.Wait()

    fmt.Println(max1, max2, max3, max4)
    var resultList = make([]int, 4)
    resultList[0] = max1
    resultList[1] = max2
    resultList[2] = max3
    resultList[3] = max4
    return max(resultList)
}

func max(list []int) int {

    length := len(list)
    if length > 1 {

        if list[0] > list[length-1] {

            return max(list[:length-1])
        } else {

            return max(list[1:length])
        }
    }
    return list[0]
}

package main

import (
    "fmt"

    "github.com/myhub/cs61a/expressions"
)

var list = []int{4, 4, 4, 4, 6, 7, 8}

func main() {
    var value = expressions.FindMax(list, len(list))
    fmt.Println(value)
}

Benchmark testing for 1e6 elements. With length value 1e8, stackoverflow occurs.

$ go test -run none -bench .
1000000 750000 500000 250000
Max element is:  1000000
goos: linux
goarch: amd64
pkg: github.com/myhub/cs61a/expressions
BenchmarkMax-4          1000000 750000 500000 250000
Max element is:  1000000
1000000 750000 500000 250000
Max element is:  1000000
1000000 750000 500000 250000
Max element is:  1000000
1000000 750000 500000 250000
Max element is:  1000000
1000000 750000 500000 250000
Max element is:  1000000
1000000 750000 500000 250000
Max element is:  1000000
1000000 750000 500000 250000
Max element is:  1000000
1000000 750000 500000 250000
Max element is:  1000000
1000000000               0.0795 ns/op
PASS
ok      github.com/myhub/cs61a/expressions    0.737s

1) Can function max() be improved in terms of condition check?

2) Is expressions package providing good abstraction(FindMax) and encapsulation, as API interface? FindMax api is hard coded for 4 thread  logic

3) sync.waitGroup is not allowing parallel operations on 4 threads. How to achieve parallelism?


texts: Repetitive replacement for expressing fractions in LaTeX

texts:
I am converting natural math expressions with fractions to Latex code.

What I have done seems to work on examples I've tested, but I'm not sure if the algorithm is safe. And maybe the string part could be improved.

Maybe a better approach could be replace the / from left to right, but how in my case target the next?

By a generic pattern that matches the 3 cases at once.
By selecting specific / and passing tests on it and remplacing it after.

I don't know how to make that.

Some examples

((a)/(b))/(c)   ->   \dfrac{\dfrac{a}{b}}{c}
(a)/((b)/(c))   ->   \dfrac{a}{\dfrac{b}{c}}
(a)/(b)/(c)/(d)    ->   \dfrac{\dfrac{\dfrac{a}{b}}{c}}{d}
((a)/(b))/((c)/(d)) ->    \dfrac{\dfrac{a}{b}}{\dfrac{c}{d}}

My try :

function ToFrac (s)
    while s:find ("/") ~= nil
    do

    -- Remplace : \dfrac{}{}/() -> \dfrac{\dfrac...}{}
    if ( s:find ( '\\dfrac%b{}%b{}/%b()' , j ) ~= nil )
    then
    x,y,num,den = s:find( '(\\dfrac%b{}%b{})/(%b())' )
    den = den:gsub( '.(.+).' , '%1' )
    s = s:gsub( '(\\dfrac%b{}%b{})/(%b())',
                            "\\dfrac{"..num.."}{"..den.."}" , 1 )
    end

    print ('### -- ', s)

    -- Remplace : ()/\dfrac{}{} -> \dfrac{()}{\dfrac...}
    if ( s:find ( '(%b()/\\dfrac%b{}%b{}' ) ~= nil )
    then
    x,y,num,den = s:find( '((%b())/(\\dfrac%b{}%b{})' )
    num = num:gsub( '.(.+).' , '%1' )
    s = s:gsub( '((%b())/()\\dfrac%b{}%b{})',
                            "\\dfrac{"..num.."}{"..den.."}" , 1 )
    end

    print ('### -- ', s)

    -- Remplace : ()/() -> \dfrac{}{}
    if ( s:find ( '%b()/%b()' , 1 ) ~= nil )
    then
        x,y,num,den = s:find( '(%b())/(%b())' )
        num = num:gsub( '.(.+).' , '%1' )
        den = den:gsub( '.(.+).' , '%1' )
        s = s:gsub( '(%b())/(%b())',
                        "\\dfrac{"..num.."}{"..den.."}" , 1 )
    end

    print ('### -- ', s)

    end -- while

    return (s)

end

s = "((a)/(b))/(c)"
print (s, ToFrac(s))

s = "(a)/((b)/(c))"
print (s, ToFrac(s))

s = "(a)/(b)/(c)/(d)"
print (s, ToFrac(s))

s = "((a)/(b))/((c)/(d))"
print (s, ToFrac(s))


texts:
I have this basic question about the efficient way to sort user-defined object. It can be done in many ways, but most of sorting algorithms at best cases is \$O(N)\$. I have come up with a fair approach to get \$O(N*log(size() + N))\$ by using std::set.

Is it a good choice in such a case?

#include <iostream>
#include <iomanip>
#include <array>
#include <string>
#include <set>

struct Student
{
    std::string studentName;
    int midTermScore;
    char grade;

    friend bool operator<(Student const & a, Student const & b)
    {
        return a.midTermScore > b.midTermScore;
    }
};

template<typename C>
void display(const C& c)
{
    std::cout << std::left
        << std::setw(10) << " Names"
        << std::setw(10) << "Exam"
        << std::setw(10) << "Grade";

    std::cout << std::setfill('-') << std::setw(28) << '\n';

    for (const auto& i : c)
    {
        std::cout << "\n " << std::setfill(' ') << std::left
            << std::setw(10) << i.studentName
            << std::setw(11) << i.midTermScore
            << std::setw(2) << i.grade;
    }
}

int main()
{
    std::array<Student, 4> a
    {
        {
            { "me",     60, 'D'},
            {"matt",    88, 'B'},
            { "john",   93, 'A'},
            {"jesseca", 82, 'B'}

        }
    };

    display(a);

    std::set<Student> sorted;

    for (auto&& i : a)
    {
        sorted.insert(i); // O(N*log(size() + N))
    }

    std::cout << "\n\nafter sorting\n\n";

    display(sorted);
}


texts:
As an exercise I repeated this Java question, but in Go: Convert string to mixed case

The objective is for every second letter to be converted to uppercase.

Go string processing is relatively new to me, and I am looking for feedback on the use of the unicode package, any other go language or library features I should be using, and of course, issues with style, convention, or possible bugs.

I have put the following in the playground as well.

package kata

import (
    "unicode"
)

// AlternateCase will return the input string modified such that alternate letters are transformed to uppercase.
//
// Note that non-letters are ignored, so in the input string `a!b` the `!` is ignored, so `b` is the second letter.
// The result of AlternateCase on `a!b` is `A!b`.
func AlternateCase(input string) string {
    runes := make([]rune, 0, len(input))
    var upper bool
    for _, c := range input {
        if unicode.IsLetter(c) {
            upper = !upper
            if upper {
                c = unicode.ToUpper(c)
            }
        }
        runes = append(runes, c)
    }
    return string(runes)
}

I have also written some test cases, and a documentation example:

package kata

import (
    "fmt"
    "testing"
)

func TestAlternateCase(t *testing.T) {
    cases := []struct{ input, output string }{
        {"hello, world!", "HeLlO, wOrLd!"},
        {"a!b", "A!b"},
        {"AAAA", "AAAA"},
        {"", ""},
        {"h", "H"},
        {"!h", "!H"},
        {"日本語", "日本語"},
        {"f日u本b語ar", "F日U本B語Ar"},
    }
    for _, c := range cases {
        got := AlternateCase(c.input)
        if got != c.output {
            t.Errorf("For input '%v' expect '%v' but got '%v'", c.input, c.output, got)
        }
    }
}

func ExampleAlternateCase() {
    hi := "hello, world!"
    fmt.Printf("The AlternateCase of '%v' is '%v'\n", hi, AlternateCase(hi))
    // Output: The AlternateCase of 'hello, world!' is 'HeLlO, wOrLd!'
}

I am looking for feedback on the test mechanisms as well.


texts: Getting the max value from a list of sums

texts:
This is my version of the knapsack challenge and I was wondering if there was a way to do it so it doesn't go through the foreach statement so many times. At the minute it goes through it thousands of times to get he closes value to the target number, which takes long time to do, I was wondering if there was a way to either do it without foreach or make it quick with the foreach.

private void btnGenerate_Click(object sender, RoutedEventArgs e)
{
    string input;
    string bag;
    int goal;
    int count = 0;

    int element;
    List<int> finalResult = new List<int>();
    do
    {
        bag = txtBag.Text;
    }
    while (!int.TryParse(bag, out goal));
    input = txtGenerate.Text;
    string[] elementsText = input.Split(' ');
    List<int> elementsList = new List<int>();
    foreach (string elementText in elementsText)
    {

        if (int.TryParse(elementText, out element))
        {
            elementsList.Add(element);
        }
    }
    Solver solver = new Solver();
    List<List<int>> results = solver.Solve(goal, elementsList.ToArray());
    int closestValue = 0;
    foreach (List<int> result in results)
    {
        count++;
        int totalValue = result.Sum(x => Convert.ToInt32(x));

        if (totalValue >= closestValue)
        {
            closestValue = totalValue;
            finalResult = result;
            txtSum.Text = closestValue.ToString();

        }
    }

    foreach (int value in finalResult)
    {
        txtCount.Text = count.ToString();

        cboResult.ItemsSource = finalResult;

    }
}

I also have a class with this in:

public class Solver
{
    public List<List<int>> mResults;
    public int closestValue = 0;
    public List<List<int>> Solve(int goal, int[] elements)
    {
        mResults = new List<List<int>>();
        RecursiveSolve(goal, 0, new List<int>(), new List<int>(elements), 0);
        return mResults;
    }

    private void RecursiveSolve(int goal, int currentSum,
    List<int> included, List<int> notIncluded, int startIndex)
    {
        for (int index = startIndex; index < notIncluded.Count; index++)
        {
            int nextValue = notIncluded[index];
            if (currentSum + nextValue <= goal && currentSum + nextValue >= closestValue)
            {
                List<int> newResult = new List<int>(included);
                newResult.Add(nextValue);
                mResults.Add(newResult);
                closestValue = currentSum + nextValue;
            }
            if (currentSum + nextValue < goal)
            {

                List<int> nextIncluded = new List<int>(included);
                nextIncluded.Add(nextValue);
                List<int> nextNotIncluded = new List<int>(notIncluded);
                nextNotIncluded.Remove(nextValue);
                RecursiveSolve(goal, currentSum + nextValue,
                    nextIncluded, nextNotIncluded, startIndex++);
            }
        }
    }
}


texts: QCombobox Case selection - Pyside2 Index via Sqlite

texts:
I have a very simple file where I have a Qcombobox Filter. When you select the filter, I run through a case on the index and output results.

So, on selection I trigger:

self.comboBox.activated.connect(self.handleActivated)

Then,

my handled function is

    def handleActivated(self, index):
        db = QSqlDatabase.addDatabase("QSQLITE")
        db.setDatabaseName("data.db")
        db.open()
        # tableView = QtWidgets.QTableView()

        if index == 0:
            sourceModel = QSqlQueryModel()
            sourceModel.setQuery(
                "SELECT url,size,content_type FROM 'google.com.au'",
                db)
            proxyModel = QSortFilterProxyModel(self)
            proxyModel.setSourceModel(sourceModel)
            self.tableView.setModel(proxyModel)
            self.tableView.setSortingEnabled(True)
        elif index == 1:
            sourceModel = QSqlQueryModel()
            sourceModel.setQuery(
                "SELECT url,size,content_type FROM 'google.com.au' WHERE content_type LIKE '%html%'",
                db)
            proxyModel = QSortFilterProxyModel(self)
            proxyModel.setSourceModel(sourceModel)
            self.tableView.setModel(proxyModel)
            self.tableView.setSortingEnabled(True)
        elif index == 2:
            sourceModel = QSqlQueryModel()
            sourceModel.setQuery(
                "SELECT url,size,content_type FROM 'google.com.au' WHERE content_type LIKE '%javascript%'",
                db)
            proxyModel = QSortFilterProxyModel(self)
            proxyModel.setSourceModel(sourceModel)
            self.tableView.setModel(proxyModel)
            self.tableView.setSortingEnabled(True)

My question is, is this the most efficient way of writing this code ? I have upto 15 filters and this will become really cumbersome in my main file.


texts:
I've written an eCommerce shopping cart handler class in PHP. Please review the code and inform me of any errors and/or badly written code and/or badly handled logics. Please also inform me of any missing functionality or security loopholes.

class Cart extends Sessions{

protected $cartProducts = array();
protected $dbLink;
protected $cartName;

public function __construct(){

    parent::__construct(); // to run the constructor of parent
    $this->cartName = 'cart';
    try{
        $this->dbLink = new db;
    }
    catch( Exception $e ){
        echo $e->getMessage() , '\n';
    }
}

public function __destruct(){
    $this->dbLink = FALSE;
}

public function cart_exist(){
    return $this->session_exist($this->cartName);
}

public function create_cart(){
    $this->create_session($this->cartName, true);
    $this->cartProducts = &$_SESSION[$this->cartName];
}

public function add_product( $data ){
    if( !$this->cart_exist() ){
        $this->create_cart();
    }
    $this->insert_value($this->cartName, $data );
}

public function display_cart(){
    $this->display_session($this->cartName);
}

public function del_from_cart( $index ){
    unset($_SESSION[$this->cartName][$index]);
}

public function update_cart_item( $index , array $data ){
    if( array_key_exists( $index , $_SESSION[$this->cartName]) ){
        $arr = &$_SESSION[$this->cartName][$index];
        foreach( $data as $key => $value ){
            $arr[$key] = $data[$key];
        }
    }
}

public function remove_cart(){
    $this->remove_session($this->cartName);
}

}


texts:
The title pretty much explains it. This is the first program I've written in assembly, so any criticism, either on programming style or saving instructions, would be appreciated.

li $t0, -1
  .data
nl: .asciiz  "\n"
  .text
loop:beq $t0, 100, exit
 add $t0, $t0, 1
 add $a0, $t0, $zero
 li $v0, 1
 syscall
 rem $t1, $t0, 3
 rem $t2, $t0, 5
 or $t3, $t1, $t2
 beqz $t3, b1
 beqz $t1, b2
 beqz $t2, b3

 la $a0, nl
 li   $v0, 4
 syscall

 j loop

b1:  li $a0, 3
 jal printb
 j loop
b2:  li $a0, 1
 jal printb
 j loop
b3:  li $a0, 2
 jal printb
 j loop

exit:li $v0, 10
 syscall

  .data
fizz: .asciiz  " Fizz\n"
buzz: .asciiz  " Buzz\n"
fizzbuzz: .asciiz  " Fizz Buzz\n"
  .text
printb:
  beq $a0, 1, l1
  beq $a0, 2, l2
  beq $a0, 3, l3
  l1: la $a0, fizz
  j print
  l2: la $a0, buzz
  j print
  l3: la $a0, fizzbuzz
  j print
print:li   $v0, 4
  syscall
  jr $ra


texts:
I'm using a very lightweight jQuery accordion with some tweaks and it's working nicely. Is there anything to improve?

JS

;(function($, doc, win) {
    "use strict";

    $.fn.accordionLite = function(){

        var sections = this.children(),
            trigger = sections.find('.accordion_trigger'),
            allContent = sections.find('.accordion_content');

        allContent.hide();
        $('.accordion_trigger.active').next('.accordion_content').show();

        trigger.click(function(){

            var activeContent = $(this).next('.accordion_content');

            if (activeContent.is(':hidden')) {
                allContent.slideUp('fast');
                activeContent.slideDown('fast');
                trigger.removeClass('active');
                $(this).addClass('active');
            } else {
                allContent.slideUp('fast');
                trigger.removeClass('active');
            }

        });

    }

})(jQuery, document, window);

Markup

        Trigger 1

Content Area 1

        Trigger 2

Content Area 2

        Trigger 3

Content Area 3


texts: Can I always use variable-length argument lists instead of arrays in argument types whenever is a choice?

texts:
I changed the withColumns() method in this class:

public static class Options {
    public String table;
    public String[] columns;

    public Options withTable(String table) {
        this.table = table;
        return this;
    }

    public Options withColumns(String[] columns) {
        this.columns = columns;
        return this;
    }
}

so it receives variable-length argument list instead of array:

    public Options withColumns(String... columns) {
        this.columns = columns;
        return this;
    }

Now I can write both:

new Options().withColumns(SubjectContract.TITLE, SubjectContract.PHOTO);

and

new Options().withColumns(new String[] { SubjectContract.TITLE, SubjectContract.PHOTO });

But of course, withColumns(SubjectContract.TITLE, SubjectContract.PHOTO) is more readable.

So are there any disadvantages in declaring argument type as a variable-length argument list, not array, whenever is a choice?


texts: Number Guessing Game in C++ without global varibles

texts:
Recently, I have gotten into C++. My past experience is some batch programming and beginner JavaScript/HTML. This language, unlike the others, has made me really think about the efficiency of my code. I am trying to do a beginner exercise from a C++ forum (Bracketing Searching) and make it as good as I possibly can. Can someone explain to me anything I am doing right or wrong? I also feel like this code is the most efficient, however it is really confusing to read, even for me.

#include <iostream> //include the input, output stream
#include <Windows.h> //include windows command library
#include <ctime> //include time library

int ask() { //ask for input and return it
    int guess;
    std::cout << "Input your guess: \n";
    std::cin >> guess;
    return guess;
}

bool calc(int guess,int num) { //takes the guess and  the number then returns true or false accordingly
    bool hasWon = false;
    if (guess > num) {
        std::cout << "Too high!\n";
    }
    else if (guess < num) {
        std::cout << "Too low!\n";
    }
    else if (guess == num) {
        std::cout << "Congrats, you are correct!\n";
        Sleep(3000);
        hasWon = true;
    }
    return hasWon;
}

void startMenu() { //Display welcome menu
    std::cout << "Welcome to my game.\n";
    std::cout << "I will think of a number from 1 to 100.\n";
    std::cout << "Guess it!\n";
}

int makeNum() {
    srand(time(0)); //Truly random number
    int num = rand() % 100; //Generate a random Number
    return num; //return the number to the main loop
}

int main() {
    startMenu(); //Display the welcome screen
    int ranNum = makeNum(); //generate the main random number
    bool hasWon = false; //set default state of win varible

    while (hasWon != true) { //while the player has NOT won keep asking
        hasWon = calc(ask(), ranNum); //Main loop of code for asking and calculating
        }
    return 0; //Terminate program
}


texts:
It is not related to GUI. I have a class with:

Private List, which is edited inside the class.
Open IReadOnlyCollection property for access to private List
Public event for notification on List changing

A list stores objects with properties. The class can changed an item's properties and notify about it. The user can only read an item's properties. I only picked this option.

class MortarInfo
{
    public double Angle { get; private set; }
    public bool State { get; private set; }
    public MortarInfo(double angle, bool state)
    {
        Angle = angle;
        State = state;
    }
}
class Mortars
{
    private List<MortarInfo> _mortarsInfo;
    private ReadOnlyCollection<MortarInfo> _readOnlyMortarsInfo;

    public Mortars()
    {
        _mortarsInfo = new List<MortarInfo>();
        _readOnlyMortarsInfo = _mortarsInfo.AsReadOnly();
    }

    public ReadOnlyCollection<MortarInfo> MortarsInfo
    {
        get { return _readOnlyMortarsInfo; }
    }
    public event ListChangedEventHandler MortarsInfoChanged;

    public void UpdateAngle(int index, double newAngle)
    {
        if (_mortarsInfo[index].Angle != newAngle)
        {
            _mortarsInfo[index] = new MortarInfo(newAngle, _mortarsInfo[index].State);
            if (MortarsInfoChanged != null)
            {
                var arg = new ListChangedEventArgs(ListChangedType.ItemChanged, index);
                MortarsInfoChanged(this, arg);
            }
        }
    }
}


texts: Using sed regular expression to extract domain name from file

texts:
I'm learning regex with sed to extract the last field from file named "test". The method I'm trying gives desired output.
Please suggest if this method Im trying is effective way of doing it. Also when should we use "-e" option with sed (please give an example — I couldn't find examples)

~# ] cat test
example.com.        4   IN  NS  b.iana-servers.net.
50times.com.        21556        IN      NS      ns1.50times.com.
example.com.        4   IN  NS  a.iana-servers.net.

~# ] cat test | sed -r 's/^[[:alnum:]]*.[[:alnum:]]*.?[a-z]*.[[:blank:]]+[0-9]+[[:blank:]]+IN[[:blank:]]+[A-Z]+[[:blank:]]+//g' | sed -r 's/\.*.$//'
b.iana-servers.net
ns1.50times.com
a.iana-servers.net


texts: Creating an array of objects for dictionaries

texts:
I wrote a piece of code that creates an array of objects based on the array of dictionaries. The problem is that my solution uses multiple loops imperatively.

Let's consider the following case. There is a class called Drug:

class Drug {

var name:String
var dosage:[(dose:String,time:String)]

init(name:String){

    self.name = name
    self.dosage = []
    }
}

I obtain the data as an array of dictionaries:

var array = [["drugName":"Amotaks", "time":"17.00", "dose":"5"], ["drugName":"Amotaks", "time":"18.00", "dose":"5"], ["drugName":"Amotaks", "time":"18.00", "dose":"5"], ["drugName":"Amotaks", "time":"17.00", "dose":"5"], ["drugName":"Claritin", "time":"17.00", "dose":"5"], ["drugName":"Claritin", "time":"18.00", "dose":"5"]]

Now is the tricky part. What is the best way to turn this data into an array of Drug objects? I am not happy with my solution because it uses nested loops and additional helper arrays thus it's very inefficient.

The purpose is to create objects without repeating their names and provide each object with an dosage array which consist of (dose, time) tuples):

var DrugArray:[Drug] = []
    var drugs:[String] = []

    for i in array

        {
        if contains(drugs, i["drugName"]! as String){
            continue
            }
        else{

            drugs.append(i["drugName"]!)
            DrugArray.append(Drug(name: i["drugName"]!))

            }

        }

    for a in DrugArray{

        for i in array {
            if i["drugName"]! == a.name
            {
                a.dosage.append(dose: i["dose"]!, time: i["time"]!)

            }

        }}

I believe there is a better way to do that, probably in a few lines of code. I tried to figure out something with basic FP functions such as map or filter but I end up with nothing.

How can I perform the operation in an elegant way (probably using more advanced functional programming)?


texts:
The script uses a financial indicator called moving averages and their crossover points to recommend best actions for stock trading (buy vs sell).

starting_cash: initial cash position
prices: list of prices (ordered by time)
crossovers: list of crossover points on the prices, crossovers[i] is a list [time_index, buy_index]
buy_index = 1 means "buy" and buy_index = 2 means "sell"

I'm just looking to simplify the script but can provide more context if anyone wants it.

def make_trades(starting_cash, prices, crossovers):

    value = [starting_cash] #set value to starting_cash
    value = []  # creating empty set?
    stock_at = 0
    cash = starting_cash

    for i in range(0,len(prices)):
        added_value = (prices[i] - prices[i-1])/prices[i-1]
        try:
            time_index = crossovers[0][0]
            buy_index = crossovers[0][1]
            if i == time_index:
                if buy_index == 1:
                    stock_at = cash
                    cash = 0
                    value.append(stock_at)
                    crossovers = crossovers[1:]
                else:
                    if(stock_at == 0):
                        cash = value[i-1]
                        value.append(value[i-1])
                    else:
                        cash = value[i-1] + value[i-1]*added_value
                        stock_at = 0
                        value.append(cash)
                    crossovers = crossovers[1:]
            else:
                if cash == 0:
                    stock_at = value[i-1] + value[i-1]*added_value
                    value.append(stock_at)
                else:
                    value.append(cash)
        except (IndexError):
            added_value = (prices[i] - prices[i-1])/prices[i-1]
            if cash == 0:
                stock_at = value[i-1] + value[i-1]*added_value
                value.append(stock_at)
            else:
                value.append(cash)
    return [round(i, 2) for i in value]


texts: Was this use of  tags in this HTML over background images better?

texts:
I saw this UI for a mobile app, but I reverse engineered it for the web. This is how it looks in my CodePen

This would be either a favorites or featured list locations to travel to. I decided to go with a
 with class of "locations"

HTML

      New York

      San Francisco

      Paris

      London

In Production, I will be building this with Meteor which uses MustacheJS templates. So this is likely how I will structure the list.

MustacheJS template (proposed)

<template name="featuredLocations">

        {{city}}

</template>

CSS

.locations {
  list-style-type: none;
  padding-left: 0;
  margin: 0;
}
.locations > li {
  border-bottom: 1px #dd4977 solid;
  height: 136px;
  width: 100%;
  position: relative;
  overflow:hidden;
}
.locations li a {
  background-color: #777;
  display: block;
  height: 100%;
  postion: relative;
  text-decoration: none;
  z-index: 1;
}

.locations > li > img {
  width: 100%;
  height: 135px;
  position: absolute; top:0; left: 0; right: 0;
  z-index: 10;
}

.locations > li > a > span {
  background-color: #dd4977;
  color: #fff;
  font-size: 21px;
  letter-spacing: 1px;
  padding: 3px 5px 0 5px;
  position: absolute; bottom: 0; left: 6px;
  z-index: 20;
}

The actual images in production will be bigger and will scale down according to the device. There will be media queries that are not shown here.


texts: Java - Object declaration out of while loop

texts:
Could you explain to me which code is better (more optimal) and why?

Vesion 1:

while(something){
Runnable task = (Runnable) taskQueue.dequeue();
Throwable  ex = null;
...
}

Version 2:

Runnable task;
Throwable ex;

while(something){
task = (Runnable) taskQueue.dequeue();
ex = null;
...
}

For me it looks like second version is optimized because variable declaration is out of while loop.


texts: Network helper class with retry logic on failure

texts:
I wrote an helper class which allow me to request the body content from a site that is created by AJAX, for doing so I'm using Puppeteer Sharp. This is the class:

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using PuppeteerSharp;

namespace App.Helpers
{
    public class NetworkHelper
    {
    /// <summary>
    /// Get the html of a page waiting for an AJAX call until the selector is visible.
    /// </summary>
    /// <param name="url">Link needed for execute the request.</param>
    /// <param name="selector">Selector to wait.</param>
    /// <param name="attempts">Max attempts until request fail.</param>
    /// <returns>Contains the html of the requested page.</returns>
    public static async Task<string> LoadAndWaitForSelector(Uri url, string selector, int attempts = 5)
    {
        try
        {
            //Create new browser page
            using (Page page = await Handler.Browser.NewPageAsync())
            {
                //Navigate on the requested content and wait for selector
                await page.GoToAsync(url.ToString(), timeout: 0);
                await page.WaitForSelectorAsync(selector); //may throw error for timeout
                return await page.GetContentAsync();
            }
        }
        catch (WaitTaskTimeoutException)
        {
            //there are other attempts, rerty
            if (attempts != 0)
            {
                attempts--;

                //add some delay
                await Task.Delay(10000);

                return await LoadAndWaitForSelector(url, selector, attempts);
            }
            throw;
        }
    }
}

Question: Could this class be improved more?

Also, the Browser is static, so each instance use the same browser for avoid memory leak:

public static Browser Browser { get; set; }

the method is called in the following way:

var html = await NetworkHelper.LoadAndWaitForSelector(
            new Uri("some url"), "#archive-tables");

thanks.


texts:
I have a textView which is displaying a string. I also have an array which keeps track of where every line begins, it stores the "start index" or NSRange.location for every line.

However, when text is inserted on one line, the start indexes of every line afterwards change. So I'm doing this:

 //i = the linenumber of the modified row
 // self.lineStartIndexes = NSMutableArray
 for (int j = i+1; j < self.lineStartIndexes.count; j++) {
     _lineStartIndexes[j] = @([(NSNumber *)[self.lineStartIndexes objectAtIndex:j] intValue]+text.length);
 }

This takes 12ms on a large text file, and it feels like it could go a lot faster without all NSNumber-conversions. I have thought about using C arrays, but I don't know the size of the array and everything became very complicated to me. What should I do to optimize this?


texts: Interface programming with Data Access Layer

texts:
I have several controls that are bound from database tables.  Putting my OOP thinking cap on I figured since all of the controls will have a SqlCommand name and an associated SqlDataReader object I decided to make the following interface to program to.

public interface IBoundControl
    {
         string GetCommandName();
         void ReadyReader(SqlDataReader rdr);
    }

For illustration's sake, consider the following to classes which implement IBoundControl interface

public class Hospital : IBoundControl
    {

        public int HospitalId { get; set; }
        public string HospitalName { get; set; }

        public string GetCommandName()
        {
            return "spGetHospitals";
        }
        public void ReadyReader(SqlDataReader rdr)
        {
            this.HospitalId = (int)rdr["HospitalId"];
            this.HospitalName = (string)rdr["HospitalName"];
        }

    }

public class Race : IBoundControl
    {
        public int RaceId { get; set; }
        public string RaceDescription { get; set; }
        public string GetCommandName()
        {
            return "spGetRaces";
        }

        public void ReadyReader(SqlDataReader rdr)
        {
            this.RaceId = (int)rdr["RaceId"];
            this.RaceDescription = (string)rdr["RaceDescription"];
        }
    }

The controls are bound to a webform by making a call to the DataAccess class's BindControl method shown below:

 public class DataAccess
    {
        private readonly string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;

        //takes in a parameter that will be bound to a web form
        public List<IBoundControl> BindControl(IBoundControl i)
        {
            //creates a list of objects which will be bound to drop down lists
            List<IBoundControl> controlList = new List<IBoundControl>();
            using (var con = new SqlConnection(cs))
            {
                //grabs the name of the sproc for whatever type 'i' is
                using (var cmd = new SqlCommand(i.GetCommandName(), con))
                {
                    con.Open();
                    cmd.CommandType = CommandType.StoredProcedure;
                    SqlDataReader rdr = cmd.ExecuteReader();
                    while (rdr.Read())
                    {
                        //the factory creates an object of whatever type 'i' is
                        ControlFactory factory = new ControlFactory();
                        IBoundControl ibound = factory.CreateControl(i);
                        ibound.ReadyReader(rdr);
                        controlList.Add(ibound);
                    }
                }
                return controlList;
            }
        }

        public class ControlFactory
        {
            public IBoundControl CreateControl(IBoundControl control)
            {
                if (control is Hospital)
                    return new Hospital();
                else if (control is Race)
                    return new Race();
                else
                    return null;
            }
        }
    }

To my surprise, this actually worked - the first time, too!  I was hoping to get some comments on how this might be improved upon, or if there's any general techniques that while this example might be too rudimentary to show, is bad practice down the road.

EDIT: When I first wrote this, the only controls that I had in mind were drop down controls(which is why both classes have two propeties, an ID and a description).


texts:
It seems useful to have a generic function to calculate the mean of all elements in a container, so I wrote one. By default it calculates the arithmetic mean, but should be able to accommodate other means (like geometric) if passed the appropriate functors.

Assumptions:

value_type can be default-constructed to yield a "zero-value" of its type

I am particularly interested in feedback on:

The validity of my assumptions
The mean() interface
How I validate my iterators
General code style.

mean.hpp

#ifndef MEAN_HPP
#define MEAN_HPP

#include <algorithm>
#include <functional>
#include <iterator>
#include <numeric>
#include <type_traits>

template <class ForwardIt, class DivOp = std::divides<>, class AddOp = std::plus<>,
          class = std::enable_if_t<
                  std::is_base_of<
                  std::forward_iterator_tag,
                  typename std::iterator_traits<ForwardIt>::iterator_category>::value>>
typename std::iterator_traits<ForwardIt>::value_type mean(ForwardIt begin,
                                                          ForwardIt end,
                                                          DivOp div = DivOp(),
                                                          AddOp add = AddOp())
{
    using value_type = typename std::iterator_traits<ForwardIt>::value_type;
    const auto sum = std::accumulate(begin, end, value_type(), add);
    const auto count = std::distance(begin, end);
    return div(sum, count);
}

#endif

Below is included some example code to demonstrate the usage of mean(). I'm less interested in feedback on the example code, but it is of course still welcome.

main.cpp

#include "mean.hpp"
#include <iostream>
#include <vector>

struct Point
{
    Point() : x(0), y(0) {}
    Point(int x, int y) : x(x), y(y) {}

    int x, y;
};

Point operator+ (const Point& lhs, const Point& rhs)
{
    return Point(lhs.x + rhs.x, lhs.y + rhs.y);
}

int main()
{
    // Works on primitives
    const std::vector<float> scalars{1, 2, 3, 4, 5, 6, 7, 8, 9};
    const auto scalarResult = mean(scalars.begin(), scalars.end());
    std::cout << scalarResult << std::endl;

    // Works on class types with appropriate operators
    const std::vector<Point> points{{1,1}, {2,2}, {3,3}};
    const auto pointDivision = [] (const Point& sum, const float count)
    {
        return Point(sum.x / count, sum.y / count);
    };
    const auto pointResult = mean(points.begin(), points.end(), pointDivision);
    std::cout << pointResult.x << " " << pointResult.y << std::endl;
}


texts: Generic function With to do a one-liner using block

texts:
I like this.  Anyone want to rain on my parade here?

public void LoadDatabasesTest()
{
    string[] args = new[] { "LoadDatabases" };
    ReportsService.Program_Accessor.Main(args);
    With(GetModel(), m => m.Databases.ToList().ForEach(c => Console.WriteLine(c.Name)));
}

void With<T>(T target, Action<T> action) where T : IDisposable
{
    using (target)
    {
        action(target);
    }
}


texts:
I have recently discovered that in type theory there is a concept of a "predicate type" which is a type \$A\$ formed out of all members of the underlying type \$U\$ that satisfy a given predicate function pred :: u -> Bool. I wondered if we can do that in Haskell, so I took this library for primes and decided to make a type for the prime numbers. This is how it looks:

module Data.Numbers.Primes.Type
    (Prime
    , getValue
    , getIndex
    , primeIndex
    , getPrime
    , maybePrime
    ) where

import Data.List (elemIndex)
import Data.Numbers.Primes

data Prime int = Prime { getValue :: int, getIndex :: Int } deriving Show

instance Integral int => Enum (Prime int) where
    toEnum = getPrime
    fromEnum = getIndex

instance Eq (Prime int) where
    x == y = getIndex x == getIndex y

instance Ord (Prime int) where
    x `compare` y = getIndex x `compare` getIndex y

-- | If a given number is prime, give its index.
primeIndex :: (Integral n, Integral i) => n -> Maybe i
primeIndex x | isPrime x = fromIntegral <$> elemIndex x primes
             | otherwise = Nothing

-- | Give n-th prime.
getPrime :: (Integral n, Integral int) => n -> Prime int
getPrime n = Prime (primes !! fromIntegral n) (fromIntegral n)

-- | If a given number is prime, give it back wrapped as such.
maybePrime :: (Integral n, Integral int) => n -> Maybe (Prime int)
maybePrime x | isPrime x = Prime (fromIntegral x) <$> primeIndex x
             | otherwise = Nothing

I'm certain this code is flawed in many ways yet unbeknownst to me, of which I hope the condescending reader would let me know so I could improve. However, there are a few points that I'm suspicious about even now:

Am I dealing with index type the right way?

Is it good to "cache" a prime's index inside the data object?

Am I doing it right?
Would it be possible and/or better to cache the indices implicitly via a memoizing function? On the pros side I see one less explicit data field which consistency could be compromised, on the contras side that we will not be able to easily save and restore data objects inbetween program runs.

Is an Int the right type for storing indices of primes, in the light of the facts that no prime has a negative index and there is a type Word for bounded unsigned integer values? (For some reason, Prelude makes no use of Word for, say, functions that deal with list indices, so, in suspicion that this design choice may have had a good motivation, I for now refrained from using the Word either.)

Maybe the index type should rather be polymorphic over the Integral class?

Is it good to use fromIntegral everywhere to make the types of the functions that deal with indices more general?

Is this type actually safe as it's intended to be? That is, can I be sure there is no way to construct a Prime data object containing an arbitrary value or an inconsistent index? For example, if I used a newtype (as I did in one of the drafts) and a derived Enum instance, I would be able to toEnum any number into prime. Does the design ensure this will not be the case ever anymore? (At least, in a reasonable usage scenario involving a non-malevolent user.)


texts: What is a better practice in bash scripts to test if string is empty: [[ -z ${value//[0-9]/""} ]] or ! [[ ${value//[0-9]/""} ]]?

texts:
I test in a bash script if a variable value contains digits only.
There are two options, both give the valid results:

validate_is_pos_int(){
local value=$1
if ! [[ ${value//[0-9]/""} ]]
then
    return 0 # True; $1 has digits only
else
    return 1 # False; $1 contains other letters besides digits
fi}

and the second (maybe more readable):

validate_is_pos_int(){
local value=$1
if [[ -z ${value//[0-9]/""} ]]
then
    return 0 # True; $1 has digits only
else
    return 1 # False; $1 contains other letters besides digits
fi}


texts: Clearing and loading values on HTML form fields

texts:
I have a bootstrap modal which contains a form that I'm using to add a new record and update existing ones.

I have a button that runs a method (showReferenceModal()) for clearing the field before showing the modal. And another button that runs a method (loadReferencesDetails(referenceId)) for loading the details before showing the modal.

function showReferenceModal() {
    ...
    $('#referenceId').val("");
    $('#name').val("");
    $('#addr').val("");
    $('#tel').val("");
    $('#updateInfo').html("");
    $('#modal').modal('show');
}

function loadReferencesDetails(referenceId) {
    ...
    $.ajax({
        ...
        dataType: 'json'
    }).done(function(response) {
        $('#referenceId').val(response.referenceId);
        $('#name').val(response.name);
        $('#addr').val(response.addr);
        $('#tel').val(response.tel);
        var updateInfo = "";
        ...
        $('#updateInfo').html(updateInfo);
        $('#modal').modal('show');
    });
}

Possible Improvements:

Is there a better way to clear the fields all at once? Because when the form gets bigger, then the method to show the modal will be bigger too. It's okay for now, but I'm thinking about extensibility. I'm new to jQuery so I don't really know if there's a method to do this.
For loading the details on the form. As you can see, the response from my Servlet returns a JSON with the same property name as the ID of the FIELD it belongs to. Maybe there's a shortcut for this too?
By the way, I have multiple modals, which have their own set of these two methods. Any tip so I can just use a single method for different modals instead of creating their own showXXXModal() and     loadXXXDetails()?


texts:
I need to read Databases which contain 44-50 Tables, with around 5 Million entries in Total (~ 100k entries per Table).

The Data consists of Positional Tracking Data in Sports (Players,Refs and the Ball) and Match-Events (Shots, Plays,Tackles,...):
Match-Events are negligible regarding performance.

Table: PlayerXYZ or Ball
-------------------------------------------
|id (int Primary Key)| x | y | z | timekey |
--------------------------------------------

Right now, it takes 86 seconds to read the Database and assign the content to a DataTable Dictionary.
That's a "Speed" of 57000 entries per second.

private async void ProcessLoadMatch()
{
    var window = Application.Current.MainWindow as MetroWindow;
    var controller = await window.ShowProgressAsync("Please wait...", "Process message", false, new MetroDialogSettings());

    controller.SetTitle("Loading Match-Data...");
    await Task.Run(() => HandleLoadMatch(controller));
    await controller.CloseAsync();

}

static bool HandleLoadMatch(ProgressDialogController ProgCtrl)
{
    string DataBasePath = @"W:\data\sqlite";
    string DataBaseName = "db";
    string dbpath = @DataBasePath + @"\" + @DataBaseName + ".sqlite";

    SQLiteConnection con = new SQLiteConnection("Data Source=" + dbpath + ";Version=3;");
    con.Open();

    DataTable tables = con.GetSchema("Tables");
    double currentTable = 0;
    double Percentage = 0;
    foreach (DataRow row in tables.Rows)
    {
        currentTable++;
        Percentage = (100 / tables.Rows.Count) * currentTable;
        string tablename = (string)row[2];
        ProgCtrl.SetMessage("Loading Data\nCurrent Table ("+currentTable+" of "+tables.Rows.Count+"): " + tablename + " ...");
        ProgCtrl.SetProgress(Percentage / 100);

        string CmdString = "SELECT * FROM " + tablename;
        SQLiteCommand cmd = new SQLiteCommand(CmdString, con);
        SQLiteDataAdapter sda = new SQLiteDataAdapter(cmd);
        DataTable MatchDt = new DataTable();
        sda.Fill(MatchDt);

        CurrentDataSet.CurrentMatch.Data.Add(tablename, MatchDt);
    }
    con.Close();
    return true;

}

CurrentDataSet.CurrentMatch.Data:

class CurrentMatch
{
    public static Dictionary<string, DataTable> Data = new Dictionary<string, DataTable>();
}

My System: Mac Mini (Late 2012)
i5-3210m clone..
16gb ram,
256GB SSD

My Question: Is there any performance potential in my code left?
I load different databases on a regular basis, so any significant performance-gains would be appreciated.

If I open my Database with a Program like SQlite Browser, the tables are being read within a second..


texts:
Problem Statement: FOXLINGS

  It’s Christmas time in the forest, and both the Fox and the Wolf
  families are celebrating. The rather large Fox family consists of two
  parents as well as \$N\$ (\$1 \leq N \leq 10^9\$) little Foxlings. The
  parents have decided to give their children a special treat this year
  – crackers! After all, it’s a well-known fact that Foxen love
  crackers.

  With such a big family, the parents can’t afford that many crackers.
  As such, they wish to minimize how many they give out, but still
  insure that each Foxling gets at least a bit. The parents can only
  give out entire crackers, which can then be divided and passed around.

  With this many children, not all of them know one another all that
  well. The Foxlings have names, of course, but their parents are
  computer scientists, so they have also conveniently numbered them from
  \$1\$ to \$N\$. There are \$M\$ (\$1 \leq M \leq 10^5\$) unique two-way
  friendships among the Foxlings, where relationship \$i\$ is described by
  the distinct integers \$A_i\$ and \$B_i\$ (\$1 \leq A_i,B_i \leq N\$),
  indicating that Foxling \$A_i\$ is friends with Foxling \$B_i\$, and vice
  versa. When a Foxling is given a cracker, he can use his tail to
  precisely split it into as many pieces as he wants (the tails of Foxen
  have many fascinating uses). He can then pass these pieces around to
  his friends, who can repeat this process themselves.

  Input

  Line 1: 2 integers, \$N\$ and \$M\$

  Next \$M\$ lines: 2 integers, \$A_i\$ and \$B_i\$, for \$i=1\ldots M\$

  Output

  A single integer – the minimum number crackers must be given out, such
  that each Foxling ends up with at least a small part of a cracker.

From the question I attempted with disjoint sets. I applied union by size along with path compression. But the constraints are very high and I could not think how to optimize this further. Offcourse I am getting TLE with solution upon submitting. So can anyone tell me any trick or idea regarding optimization?

public static void main(String[] argh) throws Exception{
        // BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Reader br= new Reader();
        int n= br.nextInt();
        int m= br.nextInt();
        int[] dj= new int[n+1];
        int[] size= new int[n+1];
        for(int i=1; i<=n; i++){
            dj[i]= i;
            size[i]= 1;
        }
        HashMap<Integer, Integer> map= new HashMap<>();
        int count=0;
        for(int i=0; i<m; i++){
            int n1= br.nextInt();
            int n2= br.nextInt();
            union(dj, size, n1, n2);
        }

        for(int i=1; i<=n; i++){
            findParent(dj, i);
        }

        for(int i=1; i<=n; i++){
            if(!map.containsKey(dj[i])){
                count++;
                map.put(dj[i], 1);
            }
        }

        System.out.println(count);
    }

    private static int findParent(int[] arr, int pos){
        if(arr[pos] == pos) return pos;
        return arr[pos]= findParent(arr, arr[pos]);
    }

    private static void union(int[] arr, int[] size, int pos1, int pos2){
        int posP1= findParent(arr, pos1);
        int posP2= findParent(arr, pos2);

        if(posP1 != posP2){
            if(size[posP1] < size[posP2]){
                int temp= posP1;
                posP1= posP2;
                posP2= temp;
            }
            arr[posP2]= posP1;
            size[posP1] += size[posP2];
        }
    }

  Note: Reader is just another fast inputting


texts: Extract index of first unique element in large array in Swift

texts:
I'm using the following code to return the first index of a unique character in a large String. It works fine until I get to large strings, where it times out.

Is there a faster way to accomplish the goal of getting a hold of the unique character's index using NSCountedSet?

Update

The string contains 25,000 characters. I refactored the original post to extract the unique chars, then cycle through the array and see if each index is contained within the uniqueChar array. It's a little faster, but not fast enough to pass Leetcode's timer.

func firstUniqChar(_ s: String) -> Int {
    guard Set(s.characters).count > 0 && s.characters.count > 0 else { return -1 }
    let stringArray = s.characters.map({String($0)})

    let countedSet = NSCountedSet(array: stringArray)

    var uniqueChars: [String] = []

    for char in countedSet {
        if countedSet.count(for: char) == 1 {
            uniqueChars.append(String(describing: char))
        }
    }

    for index in 0..<stringArray.count {
        if uniqueChars.contains(stringArray[index]) {
            return index
        }
    }

    return -1
}


texts: Is this base 62 encoding algorithm okay?

texts:
This Scala code snippet is supposed to encode a SHA1 hash in base 62.

Can you find any issues? I'm asking since I might not be able to change the algorithm and, for example, fix issues in the future.

I'd like to be able to also implement it in JavaScript in the future.

def mdSha1() = java.security.MessageDigest.getInstance("SHA-1") // not thread safe

def hashSha1Base62DontPad(text: String): String = {
  val bytes = mdSha1().digest(text.getBytes("UTF-8"))
  val bigint = new java.math.BigInteger(1, bytes)
  val result = encodeInBase62(bigint)
  result
}

private val Base62Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

def encodeInBase62(number: BigInt): String = {
  // Base 62 is > 5 but < 6 bits per char.
  var result = new StringBuilder(capacity = number.bitCount / 5 + 1)
  var left = number
  do {
    val remainder = (left % 62).toInt
    left /= 62
    val char = Base62Alphabet.charAt(remainder)
    result += char
  }
  while (left > 0)
  result.toString
}


texts: finding the conflicts in meetings given startTimes and end Times

texts:
Code to find conflicts in a list of meetings given as input.
Meetings are defined as {startTime, endTime}. I am using a Greedy Algorithm to find the conflicts. Wanted to know if there is a more efficient way of solving this problem.

Example:

Input: `meetings[] = { {1, 5} {3, 7}, {2, 6}, {10, 15}, {5, 6}, {4, 100}}`
Output: Number of Conflicts : 4

The code:

// Meeting Class
class Meeting implements Comparable<Meeting> {
    int startTime;
    int endTime;
    public Meeting(int startTime, int endTime) {
        super();
        this.startTime = startTime;
        this.endTime = endTime;
    }
    @Override
    public int compareTo(Meeting o) {
        if(this.startTime == o.startTime) return 0;
        if(this.startTime < o.startTime) return -1;
       return 1;
    }

}

Class which computes the conflicts

public class FindConflictingMeetingsProblem {
     // static function to find conflicts
    public static int findNumberOfConflicts(List<Meeting> meetings){

        // sort the meetings in ascending order of start time
        Collections.sort(meetings,new Comparator<Meeting>(){
            @Override
            public int compare(Meeting o1, Meeting o2) {
                return o1.compareTo(o2);
            }
        });

        int conflicts = 0;
        // count the conflicts
        for(int i = 0 ; i < meetings.size();i++){
            if(i > 1 && meetings.get(i-1).endTime > meetings.get(i).startTime){
                conflicts++;
            }
        }
        return conflicts;
    }

    public static void main(String[] args) {
            Meeting m1 = new Meeting(1, 2);
            Meeting m2 = new Meeting(2, 5);
            Meeting m4 = new Meeting(4, 5);
            Meeting m5 = new Meeting(7, 8);
            List<Meeting> meetingsList = new ArrayList<Meeting>();
            meetingsList.add(m1);
            meetingsList.add(m2);
            meetingsList.add(m4);
            meetingsList.add(m5);
            System.out.println(" Number of conflicts :"+findNumberOfConflicts(meetingsList));
     }
}


texts: Consumer producer implementation involving POSIX, semaphores, and locks

texts:
I am trying to get over my fear of multithreading programming and teaching myself to code using POSIX. I wrote a small version of the consumer producer problem. I am hoping I can get some feedback if it works (I think it does, as I traced the threads when my for loop was at 20 and it made sense) and what I should do to improve my code.

The semaphore starts at 4, the consumer waits one second, and then consumes a semaphore.  The producer waits between 0 and 5 seconds, then produces (increments) the semaphore value. The consumer should wait if the semaphore is at 0 until the producer frees up the resources.

#include <stdio.h>
#include <semaphore.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

sem_t my_semaphore;
pthread_mutex_t count_mutex;
void * consumerUse(void * ptr);
void * producerUse(void * ptr);

int main() {

    int value;
    pthread_t consumer, producer;
    int valConsumer =0;
    int valProducer =0;

    sem_init(&my_semaphore, 0, 4);
    sem_getvalue(&my_semaphore, &value);
    printf("The initial value of the semaphore is %d\n", value);

    for(int i=0; i < 100; i++)
    {

        valConsumer = pthread_create(& consumer, NULL, consumerUse, (void*)(intptr_t) value);
        if(valConsumer != 0)
        {
            fprintf(stderr, "Error - pthread create () return code: %d\n", valConsumer);
            exit(EXIT_FAILURE);
        }

        valProducer = pthread_create(& producer, NULL, producerUse, (void*) (intptr_t)value);
        if(valProducer != 0)
        {
            fprintf(stderr, "Error - pthread create () return code: %d\n", valProducer);
            exit(EXIT_FAILURE);
        }

    }
    pthread_join( consumer, NULL);
    pthread_join( producer, NULL);
    printf("End program\n");
    return 0;
}

void *consumerUse(void * ptr)
{
    sleep(1);
    int value;
    sem_getvalue(&my_semaphore, &value);
    printf("Before wait: %d\n", value);
    pthread_mutex_lock(&count_mutex);
    sem_wait(&my_semaphore);
    pthread_mutex_unlock(&count_mutex);
    sem_getvalue(&my_semaphore, &value);
    printf("Consumer semaphore value: %d\n", value);
    return 0;
}

void *producerUse(void * ptr)
{

    int pause = rand() % 5;
    sleep(pause);
    int value;
    sem_getvalue(&my_semaphore, &value);
    printf("Before post: %d\n", value);
    if(value < 4)
    {

        sem_post(&my_semaphore);
        sem_getvalue(&my_semaphore, &value);
        printf("Producer semaphore value: %d\n", value);
    }
    return 0;
}


texts: Improvements and advice for my Cache class

texts:
After reading a bit about the System.Runtime.Caching in the .net 4 framework I've added a simple Cache class to my application.

Can I improve it or add additional useful functionality? Typing it out here I see that the cache checking is somewhat duplicated; could this be refactored?

Note: the two properties SuperUsers and TemplateLocation are just for an example of how the class would be used. Most properties would be a string or list.

/// <summary>
/// Cache class as singleton to make those often used
/// values that may change just that bit more speedy.
/// </summary>
/// <remarks>
/// Jon Skeets' singleton http://csharpindepth.com/Articles/General/Singleton.aspx
/// </remarks>
public sealed class Cacher
{
    private readonly ObjectCache _cache = MemoryCache.Default;
    public CacheItemPolicy Policy { get; set; }

    private static readonly Cacher instance = new Cacher();

    static Cacher()
    { }

    private Cacher()
    {
        // expiration policy default
        Policy = new CacheItemPolicy
        {
            AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(10.0)
        };
    }

    public static Cacher Instance
    {
        get { return instance; }
    }

    public string TemplateLocation
    {
        get
        {
            var loc = _cache["templatelocation"] as string;
            if (string.IsNullOrEmpty(loc))
            {
                // hardcoded for test purposes
                _cache.Set("templatelocation", getTemplateLocation(), Policy);
                loc = _cache["templatelocation"] as string;
            }
            return loc;
        }
    }

    public List<string> SuperUsers
    {
        get
        {
            var superUsers = _cache["superusers"] as List<string>;
            if (superUsers == null)
            {
                // empty, so stick values in the cache
                _cache.Set("superusers", GetSuperUsers(), Policy);
                superUsers = _cache["superusers"] as List<string>;
            }
            return superUsers;
        }
    }

    private string getTemplateLocation()
    {
        // hardcoded for test purposes
        return @"C:\";
    }

    private List<string> GetSuperUsers()
    {
        // hardcoded for test purposes
        return new List<string> {"John", "Anne", "Mark"};
    }

    public void Clear()
    {
        foreach (var cacheitem in _cache)
            _cache.Remove(cacheitem.Key);
    }
}

and using the class:

string location = Cacher.Instance.TemplateLocation;
List<string> sUsers = Cacher.Instance.SuperUsers;