texts: Correct usage of MVVM and object for method

texts:
I'm writing my first C# Windows Store app and am learning C# from scratch. I'm trying to implement MVVM as I understand it and object orientated patterns, obviously though I'm expecting to be doing it wrong so looking for pointers as to what I should improve.

Below is a method that gets called when a user either clicks a 'Search' XAML control, or hits return in the search textbox control.

The comments should explain the code. I feel like I probably have too much code in for a event method so please advise how I would restructure it.

  private void SubmitSearch(object sender, RoutedEventArgs e)
    {
        //New Validation object
        ViewModels.Validation validation = new ViewModels.Validation();

        // Capture user entered term and check is valid
        // submit appropriate message.
        var searchValue = searchTerm.Text.ToString();
        dynamic validateInput = validation.inputNullCheck(searchValue);

        int? errorCode = validateInput.ErrorCode;

        if (errorCode == 0)
        {
            SubmitAction(searchValue);
        }
        else
        {
            DisplayTerms(validateInput);
        }

    }

My SubmitAction method:

public async Task<object> SubmitAction(string searchValue)
    {

        // Query webservice/database through Model and return response
        dynamic response = await new ViewModels.Search().QueryRequest(searchValue);
        DisplayTerms(response);

        //This is here only because I needed the method to be async, which in turn requires a
        // value to be returned. Ideally it would be async and end after DisplayTerms(response);
        return response;
    }

DisplayTerms method:

private void DisplayTerms(object value)
    {

        ListView termsList = termsListContainer;
        dynamic searchResponse = value;

        int count = searchResponse.Count;

        // This will eventually be a loop through the returned object
        // it is hardcoded at the moment because I am debugging something.
        termsList.Items.Add(searchResponse[0].TermName);
    }

Validation class:

class Validation
{

    // Temporarily 0 = success, 1 = error
    public int? ErrorCode { get; set; }
    public string ErrorName { get; set; }
    public string ErrorMessage { get; set; }

    //Constructor
    public Validation ()
    {

    }

    // Check if user input was empty
    public object inputNullCheck(string input)
    {
        if (input != "")
        {
            this.ErrorCode = 0;
            this.ErrorName = "Success";
            this.ErrorMessage = "Valid input received";
            return this;
        }
        else
        {
            this.ErrorCode = 1;
            this.ErrorName = "Input Empty";
            this.ErrorMessage = "You have not input anything.";
            return this;
        }
    }
}


texts:
Problem statement:

  Write a CashWithDrawal function from an ATM which, based on user
  specified amount, dispenses bank notes. Ensure that the following is
  taken care of:

  Minimum number of bank notes are dispensed
  Availability of various denominations in the ATM is maintained

  Code should support parallel withdrawals (i.e two or more customers
  can withdraw money simultaneously).  Take care of exceptional
  situations.

public class ATMMachine {
    private Map<Integer, Integer> notes;

    public ATMMachine(Map<Integer, Integer> notesMap){
        notes = notesMap;
    }

    private boolean isCorrectAmt(int amt){
        return amt%10==0 ? true : false;
    }

    private synchronized void reduceBalance(int denomination, int noToReduce){
        int amt = notes.get(denomination);
        notes.remove(denomination);
        notes.put(denomination, amt-noToReduce);
    }

    public synchronized Integer getATMBalance(){
        int balance = 0;
        for(Integer denominator: notes.keySet()){
            balance = balance + (denominator * notes.get(denominator));
        }
        return balance;
    }

    public synchronized Map<Integer, Integer> withdrawAmt(int amt){
        Map<Integer, Integer> returnedMap = new HashMap<Integer, Integer>();

        if(!isCorrectAmt(amt)){
            System.out.println("Please enter amount in multiple of 10");
            return returnedMap;
        }

        //get sorted denominations
        TreeSet<Integer> denominations = new TreeSet<Integer>(notes.keySet());
        Iterator<Integer> iter = denominations.descendingIterator();

        while(amt > 0 ){
            int denomination = iter.next();
            int noOfNotes = amt< denomination ? 0 : amt/denomination;
            returnedMap.put(denomination, noOfNotes);
            amt = amt - (denomination * noOfNotes);
            reduceBalance(denomination, noOfNotes);
        }
        return returnedMap;
    }

    public static void main(String agrs[]){
        Map<Integer, Integer> notesMap = new HashMap<Integer, Integer>();
        notesMap.put(500, 10);
        notesMap.put(100, 20);
        notesMap.put(50, 50);
        notesMap.put(10, 30);

        ATMMachine atm = new ATMMachine(notesMap);

        System.out.println("Current balance is : " + atm.getATMBalance());
        System.out.println("withdraw amt 200" + atm.withdrawAmt(800));
        System.out.println("balance after withdrawing " + atm.getATMBalance());

        ATMUser user = new ATMUser(atm, 4000);
        Thread userThread1 = new Thread(user);
        Thread userThread2 = new Thread(user);
        userThread1.start();
        userThread2.start();
    }
}

public class ATMUser implements Runnable {

    ATMMachine atm;
    int amtToWithdraw;

    public ATMUser(ATMMachine atm, int amtToWithdraw){
        this.atm = atm;
        this.amtToWithdraw = amtToWithdraw;
    }

    @Override
    public void run() {
        System.out.println("Balance in ATM is " + atm.getATMBalance());
        System.out.println("withdrawin  amt : " + amtToWithdraw);
        System.out.println("withdrawn : " + atm.withdrawAmt(amtToWithdraw));
        System.out.println("Balance after withdraw is : " + atm.getATMBalance());
    }
}


texts: MergeSort implementation with java.util.List passed as argument, not returned

texts:
I'm working on an implementation of MergeSort which sorts a List given as an argument. As follows

public class MergeSort implements Sort {
    @Override
    public <E extends Comparable<E>> void sort(List<E> list) {
        final int length = list.size();
        List<E> left = null;
        List<E> right = null;
        if (length == 1 || length == 0) {
            return;
        } else {
            left = new ArrayList<>(list.subList(0, length/2));
            right = new ArrayList<>(list.subList(length/2, length));
            sort(left);
            sort(right);
        }
        // can these be improved?
        list.clear();
        list.addAll(merge(right, left));
    }

    private <E extends Comparable<E>> List<E> merge(List<E> right, List<E> left) {
        List<E> newList = new LinkedList<>();
        int rightIndex = 0, leftIndex = 0;
        while (rightIndex < right.size() && leftIndex < left.size()) {
            E rightElement = right.get(rightIndex);
            E leftElement = left.get(leftIndex);
            if (rightElement.compareTo(leftElement) > 0) {
                newList.add(leftElement);
                leftIndex++;
            } else {
                newList.add(rightElement);
                rightIndex++;
            }
        }

        // add remaining
        while (leftIndex < left.size()) {
            newList.add(left.get(leftIndex));
            leftIndex++;
        }
        while (rightIndex < right.size()) {
            newList.add(right.get(rightIndex));
            rightIndex++;
        }
        return newList;
    }
}

I want to do the sorting on the List that's passed as an argument, not return a new List. I feel, however, that calling clear() and addAll() a number of times might slow things down. How can I avoid these calls?


texts: Truly private JavaScript class members (ES6)

texts:
I've found pretty simple and clear pattern which can be used to make any data members truly private (invisible, inaccessible) without affecting class behavior (no prototypes and Object.XXX magics required).

This "Lock & Key" pattern uses closures with ES6 Symbol's and Proxy approaches:

const MyClass = (()=>{

    const _PRIVATE_STORAGE = Symbol('PRIVATE_STORAGE'); // visible, see below
    const _PRIVATE_KEY     = Symbol('PRIVATE_KEY');     // fully hidden

    function privateFun(newValue) {
        const _this = this[_PRIVATE_STORAGE](_PRIVATE_KEY);
        _this.private_value = newValue;
        console.log('changed: private_value = ' + _this.private_value);
    }

    class MyClass {
        constructor() {
            // Truly private data
            const _this = {};

            // "Lock" closure function (!)
            this[_PRIVATE_STORAGE] = (key) => (
                key === _PRIVATE_KEY ? _this : undefined);

            // Any initialization
            _this.private_value = 0;
        }

        publicFun1() {
            const _this = this[_PRIVATE_STORAGE](_PRIVATE_KEY);
            console.log('private_value = ' + _this.private_value);
        }

        publicFun2(newValue) {
            return privateFun.call(this, newValue);
        }
    }

    return MyClass;

})();

const obj = new MyClass;
obj.publicFun1();
obj.publicFun2(42);
console.log(Object.getOwnPropertyNames(obj));
console.log(Object.getOwnPropertySymbols(obj));
console.log(obj[Object.getOwnPropertySymbols(obj)[0]]);
console.log(obj[Symbol('PRIVATE_KEY')]);

Output:

private_value = 0
changed: private_value = 42
[]
[ Symbol(PRIVATE_STORAGE) ]
[Function]
undefined

Pros:

No memory overhead, no WeakMap's.
Private properties are truly inaccessible and innumerable (except for one Symbol).
Private methods are truly hidden (well known approach with call invocation).
"Class" is just a standard JavaScript function: any kind of inheritance, prototype extension, mixins, decorators etc. are supported.

Cons:

+2 indirection levels (in comparison with simplest "name conventions" approach), so +2 function calls overhead.

Thank you in advance for review, I'm looking for any suggestions/critique thoughts and maybe additional pros-cons points and underwater rocks.

In addition: I didn't find any completely identical approach mentioned in the web, so it may be a known technique. Otherwise, I've found it a very interesting and useful task to investigate and implement.


texts: jQuery animation and rotation effects for a WordPress site

texts:
What is the best way to tidy up JavaScript code I have written? It seems very long winded, any suggestions to shorten it?

Note: I'm running it on Wordpress which runs jQuery in nonconflict mode, hence the insane amounts of jQuery.().

jQuery("document").ready(function (jQuery) {

    if (jQuery(window).width() < 960) {
        jQuery(".main").animate({
            "top": "22%"
        });
        jQuery('#tblcontents').toggle(function () {
            jQuery(".main").fadeOut(1000);
        }, function () {
            jQuery(".main").fadeIn(1000);
            jQuery(".main").animate({
                "top": "22%"
            });

        });

    } else {}

    jQuery('.menu-button').click(function () {
        jQuery("#sb-container div").css("transform", "rotate(0deg)");
        jQuery("#sb-container div").css("-webkit-transform", "rotate(0deg)");
        jQuery("#sb-container div").css("-ms-transform", "rotate(0deg)");
        jQuery("#sb-container div").css("-moz-transform", "rotate(0deg)");
        jQuery("#sb-container div").css("-o-transform", "rotate(0deg)");
        jQuery(".main").animate({
            "right": "1%"
        }, "slow");
    });

    jQuery(function () {
        jQuery('.toggle_div').toggle(function () {
            jQuery(".main").animate({
                "right": "50%"
            }, "slow");
        }, function () {
            jQuery(".main").animate({
                "right": "1%"
            }, "slow");
        });
    });

    jQuery(".pulse").effect("pulsate", {
        times: 100
    }, 2000).click(function () {
        jQuery(".pulse").effect().stop(true, true);
        jQuery(".pulse").animate({
            "opacity": "1"
        }, "fast");
    });
    jQuery('.thumb').click(function () {
        jQuery("#sb-container div").css("transform", "rotate(0deg)");
        jQuery("#sb-container div").css("-webkit-transform", "rotate(0deg)");
        jQuery("#sb-container div").css("-ms-transform", "rotate(0deg)");
        jQuery("#sb-container div").css("-moz-transform", "rotate(0deg)");
        jQuery("#sb-container div").css("-o-transform", "rotate(0deg)");
        jQuery("#sb-container").animate({
            "left": "0px"
        }, "slow");
        jQuery(".main").animate({
            "right": "1%"
        }, "slow");
    });

    jQuery(window).scroll(function () {
        if (jQuery(this).scrollTop() > 20) {
            jQuery("#sb-container div").css("transform", "rotate(0deg)");
            jQuery("#sb-container div").css("-webkit-transform", "rotate(0deg)");
            jQuery("#sb-container div").css("-ms-transform", "rotate(0deg)");
            jQuery("#sb-container div").css("-moz-transform", "rotate(0deg)");
            jQuery("#sb-container div").css("-o-transform", "rotate(0deg)");
            jQuery(".main").animate({
                "right": "1%"
            }, "slow");

        } else {
            jQuery("#sb-container").draggable()
        }
    });

});

jQuery(function () {
    jQuery("#sb-container").draggable()
});

How do I go about reducing the amount of code shown here? What are the best practices and what am I missing? Also, do I need the else statements querying the window width since they don't have any functions in them for the most part?


texts:
I've implemented Luhn checksum in Python version 3. I want your comments and opinion about my code. I know it's embarrassing code and that it doesn't follow python best practices but it works!.

The x in doubledigit parameter means that if the boolean is False, the index of the number is odd so we don't have to double it, if it is True it means the index is even, so we double it.

import ast

def  doubledigit(n,x) :

    if x is  True:

        doubledigit = n *2
        sum=0
        if doubledigit >= 10 :
            sum = 1 + doubledigit % 10
        else: sum = doubledigit
    else:
        sum = n

    return (sum)
def sum ():
    total =0
    prop = int(input("enter how many digits you want: " ))
    for i in range (0,prop):
        n = int(input("Enter your digit: " ))
        x = input("Enter True or False: ")
        total = total+doubledigit(n,ast.literal_eval(x))

    return total
def findx (n):
    if (n % 10 == 1 ):
        print("the check digit is 9")

        n += 9
    if (n % 10 == 2 ):
        print("the check digit is 8")

        n += 8
    if (n % 10 == 3 ):
        print("the check digit is 7")
        n += 7
    if (n % 10 == 4 ):
        print("the check digit is 6")

        n += 6
    if (n % 10 == 5 ):
        print("the check digit is 5")

        n += 5
    if (n % 10 == 6 ):
        print("the check digit is 4")

        n += 4
    if (n % 10 == 7 ):
        print("the check digit is 3")

        n += 3
    if (n % 10 == 8 ):
        print("the check digit is 2")

        n += 2
    if (n % 10 == 9 ):
        print("the check digit is 1")

        n += 1
    if (n % 10 == 0):
        print("vaild checksum")
    return n
print(findx(sum()))


texts:
I'm trying to make a simple app to help me store data about food to use this database in a future diet application. What can I do to improve the code? What part of code should I make a class etc.?

    #include <iostream>
    #include <vector>
    #include <string>
    #include <map>
    #include <iterator>

    using namespace std;

    struct food
    {
        int mass;
        double kcal;
        double prot;
        double carb;
        double fat;
    };

    map<string, food> foodMap_prot;
    map<string, food> foodMap_carb;
    map<string, food> foodMap_fat;
    int main()
    {

        int mass;
        double kcal;
        double prot;
        double carb;
        double fat;
        string name;
        cout << "Enter a name for a product: ";
        getline(cin,name,'\n');
        cout << "\nmass of [" << name << "]: ";
        cin >> mass;
        cout << "\ncalories of [" << name << "]: ";
        cin >> kcal;
        cout << "\nprotein in [" << name << "]: ";
        cin >> prot;
        cout << "\ncarbs in [" << name << "]: ";
        cin >> carb;
        cout << "\nfat in [" << name << "]: ";
        cin >> fat;
        string kategory;
        double factor;
        kcal /= 100;
        prot /=100;
        carb /=100;
        fat /=100;
        food temp1 = {mass, mass*kcal, mass*prot, mass*carb, mass*fat};
        map<string, food>::iterator itr, koniec;
        if(prot>carb && prot>fat)
        {
            factor = prot*100/7;
            mass = mass/factor;
            temp1 = {mass, mass*kcal, mass*prot, mass*carb, mass*fat};
            foodMap_prot[name] = temp1;
            itr = foodMap_prot.find(name);
            koniec = foodMap_prot.end();
            kategory = "Protein";
}
else if(carb>prot&&carb>fat)
{
    factor = carb*100/9;
    mass = mass/factor;
    temp1 = {mass, mass*kcal, mass*prot, mass*carb, mass*fat};
    foodMap_carb[name] = temp1;
    itr = foodMap_carb.find(name);
    koniec = foodMap_carb.end();
    kategory = "Carbs";
}
else if(fat>prot&&fat>carb)
{
    factor = fat*100/1.5;
    mass = mass/factor;
    temp1 = {mass, mass*kcal, mass*prot, mass*carb, mass*fat};
    foodMap_fat[name] = temp1;
    itr = foodMap_fat.find(name);
    koniec = foodMap_fat.end();
    kategory = "Fat";
}

for(;itr!=koniec; ++itr)
{
    cout <<"\n\nyou added a new product \t[" << name <<"]";
    cout <<"\n\ncategory: \t\t\t" << kategory;
    cout <<"\n\nmass of one block of [" << name << "]: \t" << itr->second.mass<<"g";
    cout <<"\n\ncalories in [" << name << "]: \t" << itr->second.kcal<<" kcal";
    cout << "\n\nprotein [" << name << "]: \t"<< itr->second.prot<<"g";
    cout <<"\n\ncarbs [" << name << "]: \t" << itr->second.carb<<"g";
    cout << "\n\nfat [" << name << "]: \t" << itr->second.fat<<"g";
}

    }


texts: Redirecting to the appropriate URL for some type of notification

texts:
I have a polymorphic notification model with action attribute. When user clicks on a notification he/she should be redirected to given page the notification refers to through notifiable.

What is the best way to refactor the following method?

_notification.html.erb

<%= link_to checking_decreasing_user_notifications_path(current_user, notification: notification) do %>

notifications controller

def checking_decreasing
  notification = Notification.find(params[:notification])
  current_user.decreasing_comment_notification_number(notification)
  redirect_to notification_redirection_path(notification)
end

def notification_redirection_path(notification)
  notifiable_type = notification.notifiable_type
  notifiable_id = notification.notifiable_id
  action = notification.action
  if action == "commented"
    route = case notifiable_type
            when "Post"
              posts_path(anchor: "post_#{notifiable_id}")#{}"/posts#post_#{notifiable_id}"
            when "Product"
              product_path(notifiable_id, anchor: "comment-panel")#/products/#{notifiable_id}#comment-panel"
            when "ProductLead"
              product_product_lead_path(product_id, notifiable_id, anchor: "comment-panel")#{}"/products/#{product_id}/#{notifiable_type}/#{notifiable_id}#comment-panel"
              product_lead = ProductLead.find(notifiable_id)
              product_id = product_lead.product_id
            when "ProductCustomer"
              product_customer = ProductCustomer.find(notifiable_id)
              product_id = product_customer.product_id
              product_product_customer_path(product_id, notifiable_id, anchor: "comment-panel") #/products/#{product_id}/#{notifiable_type}/#{notifiable_id}#comment-panel"
            end
  elsif action == "invited"
    if notifiable_type == "Product"
      product_path(notifiable_id, anchor: "product-invitation-well")
    elsif notifiable_type == "ProductCustomer"
      product_customer = ProductCustomer.find(notifiable_id)
      product_id = product_customer.product_id
      product_product_customer_path(product_id, notifiable_id)
    end
  elsif action == "accepted"
    if notifiable_type == "Product" #team member invitation
      product_product_owner_panels_path(notifiable_id)
    elsif notifiable_type == "ProductCustomer" #referencer invitation
      product_customer = ProductCustomer.find(notifiable_id)
      product_id = product_customer.product_id
      product_product_owner_panels_path(product_id)
    end
  elsif action == "wrote"
    product_customer = ProductCustomer.find(notifiable_id)
    product_id = product_customer.product_id
    product_product_customer_path(product_id, notifiable_id)
  end
end


texts: Volatility updating with Heston-Nandi model

texts:
I'm trying to program a volatility updating rule using iteration. I start with the well-known Heston-Nandi model where the returns dynamics are:

$$
\left\{
  \begin{array}{rcl}
    R_{t+1} &=& r + \gamma h_{t+1} + \sqrt{h_{t+1}} z_{t+1}\\
    h_{t+1} &=& \beta_0 + \beta_1 h_t + \beta_2\left(z_t - \beta_3 \sqrt{h_t}\right)^2
  \end{array}
\right.
$$

where

\$z_t\$ is an IID standard normal random variable
\$h_t\$ is time-varying squared volatility
\$\beta_0 > 0,\ \beta_1 \ge 0,\ \beta_2 \ge 0\$, and \$\gamma > -\frac{1}{2}\$.

I want to do is to write the code associate to the volatility updating rule, explained in this algorithm:

Define \$h_0 = c\$ equals the given unconditional variance  which is constant,
Iteration for \$t \in \{1, 2, \cdots, n\}\$:

$$
\left\{
  \begin{array}{rcl}
    h_{t+1} &=& \beta_0 + \beta_1 h_t + \beta_2\left(z_t - \beta_3 \sqrt{h_t}\right)^2 \\
    z_t     &=& \frac{[R_t - r - \gamma h_t]}{\sqrt{h_t}}
  \end{array}
\right.
   $$

to obtain the returns based proxy for spot variances \$(h_t^R)_t\$. Which yields an updating function that exclusively involves observation:

$$ h_{t+1} = \beta_0 + \beta_1 h_t + \frac{\beta_2}{h_t} \left( R_t - r - (\beta_3 + \gamma)h_t \right)^2$$

My program is the following:

library(fGarch)

T=3000
    # For the example I simulate a GARCH
    #process parameters
    eta = 0.2 #eta = 0 is equivalent to Geometric Brownian Motion
    mu = 100 #the mean of the process

    #GARCH volatility model
    specs = garchSpec(model = list(omega = 0.000001, alpha = 0.5, beta = 0.4))
    sigma = garchSim(spec = specs, n = T)

    P_0 = mu #starting price, known
    P = rep(P_0,T)

    for(i in 2:T){
      P[i] = P[i-1] + eta * (mu - P[i-1]) + sigma[i] * P[i-1]
    }

    # Set the parameters :
para<-c(0.1,0.2,0.3,0.4,0.5,0.7) # (beta_0,beta_1, beta_2, beta_3, r, gamma)
    # Iteration to obtain the volatility associate to the model :

vol = c()
vol[1]=sd(P)
for (i in 2:length(P)){
      para_vol <- para[1:6]
      vol[i]=para_vol[1]+ (para_vol[2]*vol[i-1])+ (para_vol[3]/vol[i-1])*(P[i-1]-para_vol[5]-(para_vol[4]+para_vol[6])*vol[i-1])
      }
vol

This is an example where I simulate a GARCH (as data set). I am trying to extract the volatility associated with the Heston-Nandi model.

I know I'm using a lot of bad things for R, but I could not figure out a better solution. Are there any corrections or suggestions needed to improve this process?


texts:
This is just simple code to practice the use of virtual functions from a practice challenge in HackerRank. Could you give me some advice about the best practices and style?

This is just a simple exercise from HackerRank

#include <string>
#include <array>
#include <numeric>
#include <iostream>
#include <algorithm>

class Person {
    protected:
    std::string name;
    int age;
    public:
    virtual void getdata() = 0;
    virtual void putdata() const = 0;
};
class Student final : public Person {
    static inline int id_count = 0;
    std::array<int,6> marks;
    int cur_id;
    public:
    Student(){
        cur_id = ++Student::id_count;
    }
    void getdata() override {
        std::cin >> this->name;
        std::cin >> this->age;
        for (auto &mark : marks) {
            std::cin >> mark;
        }
    }
    void putdata() const override{
        std::cout << name << " " << age << " " << std::accumulate(marks.begin(), marks.end(), 0) << " " << cur_id << std::endl;
    }
};

class Professor final : public Person {
    static inline int id_count = 0;
    int publications;
    int cur_id;

    public:
    Professor(){
        cur_id = ++Professor::id_count;
    }
    void getdata() override {
        std::cin >> this->name;
        std::cin >> this->age;
        std::cin >> this->publications;
    }
    void putdata() const override {
        std::cout << name << " " << age << " " << publications << " " << cur_id << endl;
    }
};

Code provided by the question (cannot be edited):

 int main(){
    int n, val;
    std::cin>>n; //The number of objects that is going to be created.
    Person *per[n];

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

        std::cin>>val;
        if(val == 1){
            // If val is 1 current object is of type Professor
            per[i] = new Professor;

        }
        else per[i] = new Student; // Else the current object is of type Student

        per[i]->getdata(); // Get the data from the user.

    }

    for(int i=0;i<n;i++)
        per[i]->putdata(); // Print the required output for each object.

    return 0;

}


texts: Comparing numbers and making a calculation

texts:
I have a piece of javascript I wrote for a recent work project that is essentially taking a deviceorientation event object, taking either the beta value or gamma value of that object and makes a calculation.

While I can't necessarily put my exact code here just in case that breaks any of the agreements I signed, the general idea is as follows. Just a note: this code is already headed for production and I'm not looking for someone to do my work for me. I'm asking this so I can use it for new code in the future. I like to keep functions small and avoid using complex structures like the one below, but my time in this field is still limited and I could not think of a better way to handle this.

The names of functions/variables have been changed to protect the identity of the innocent. I'm also skipping a few of the in between functions as I'm just wondering if there's a cleaner way to handle this calculation.

Code starts with adding an event listener:

window.addEventListener('deviceorientation', doSomeStuff, false);

doSomeStuff eventually makes a call to makeCalculation and passes along the event object:

function doSomeStuff(event){
    // Other stuff happens...
    makeCalculation(event);
}

At this point, I want to make a calculation based on the beta or gamma value of that event object. I have a minimum and maximum range I want stay within, as well as a slight alteration to the calculation when the value is between another range within the min-max range. I will use event.gamma as an example and ignore the logic to determine whether I want to use beta or gamma;

function makeCalculation(e){
    var value;

    if (Math.round(e.gamma) === 0) {
        value = 0;
    } else if (e.gamma < -2) {
        value = // Some Calculation
    } else if (e.gamma > 2) {
        value = // Some Other Calculation
    } else {
        value = // Yet a different calculation
    }

    return value;
}

Is there a better way to make number comparisons of this nature without having to creating a nasty looking if/else if block?


texts: Porting a web-based POS system to Android

texts:
I'm currently porting a web-based POS system to Android. The Android version uses NavigationDrawer to navigate between menus.

What I need a code review on is my current approach in loading fragments upon selected an item from navigation drawer. I'm using reflection to achieve my case.

MainActivity.java

@Override
    public void onNavigationDrawerItemSelected(String menuItemText) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        BaseFragment fragmentToOpen = null;
        Method newInstanceMethod = null;
        try {
            newInstanceMethod = AvailableMenuList.MENU_ITEM_TABLE.get(menuItemText).getMethod("newInstance", null);
            fragmentToOpen = (BaseFragment) newInstanceMethod.invoke(fragmentToOpen, null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        fragmentManager.beginTransaction()
                .replace(R.id.container, fragmentToOpen, menuItemText)
                .addToBackStack(menuItemText)
                .commit();
    }

HashMap implementation of available POS functions in Android version:

    public class AvailableMenuList {
        private AvailableMenuList() {} //Disable object instantiation

            public static final HashMap<String, Class<BaseFragment>> MENU_ITEM_TABLE = new HashMap() {{
                put("Announcement", AnnouncementListFragment.class);
                put("Board", BoardListFragment.class);
                put("SalesRegistration", SalesRegFragment.class);
                put("SalesRecords", SalesRtvFragment.class);
                put("OrderRegistration", OrderRegFragment.class);
                put("OrderRecords", OrderRtvFragment.class);
            }};
        }
    }

Is there a better approach of instantiating a new Fragment (by calling newInstance) instead of using reflection? Currently, there's only 6 functionalities but there's going to be at least 30 more in the future.


texts: Partitioning input strings by even and odd indexes

texts:
I have been trying to learn javascript for a year now, and have just embarked on HackerRank's 30 days of code. After a couple of days I finally solved this problem. Here is the task (if you click the link, press x to the signup page):

  Task

  Given a string S of length N that is indexed from 0  to N-1, print its even-indexed and odd-indexed characters as  space-separated strings on a single line (see the Sample below for more detail).

  Sample Input

  2
     Hacker
     Rank

  Sample Output

  Hce akr
     Rn ak

Here is my solution. Any performance optimizations I could make here?:

function processData(input) {
    //Enter your code here

    //split the string into an array
    let words = input.split("\n").slice(1),
    odd = "",
    even = "",
    newStr = "";
    //turn each string inside the array into its own array
    let wordsArr = words.map((val) => {
        return val.split("");
    })
    //outer loop for the outer array
    for (let i = 0, len = wordsArr.length; i < len; i++){
          //inner loop for the inner arrays
        for (let j = 0, len2 = wordsArr[i].length; j < len2; j++){
         //if the index is even or odd, add to the respective strings
             if (j % 2 === 0){
                even += wordsArr[i][j]
            } else if (j % 2 !== 0) {
                odd += wordsArr[i][j];
            }

            //if the end of the array is detected, print the string
            //and set odd/even strings to be blank for the next iteration
            if (j == len2 - 1){
                newStr = `${even} ${odd}`;
                even = "";
                odd = "";
                console.log(newStr);
            }
    }
}

}


texts: Print odd and even numbers using two threads in Java

texts:
I was asked below question in an interview where I need to print out even and odd numbers using two threads so I came up with below code one without synchronization and other with synchronization.

/**
 * Without synchronization
 *
 */
class Print {
  private static final int MAX = 10;
  private static int count = 1;
  private boolean isOdd = true;

  public void printEven() {
    while (true) {
      if (count > MAX)
        break;
      if (!isOdd) {
        System.err.println(Thread.currentThread().getName() + " : " + count++);
        isOdd = true;
      }
    }
  }

  public void printOdd() {
    while (true) {
      if (count > MAX)
        break;
      if (isOdd) {
        System.err.println(Thread.currentThread().getName() + " : " + count++);
        isOdd = false;
      }
    }
  }
}

/**
 * Using synchronization
 *
 */
class Print2 {
  private static final int MAX = 10;
  private static int count = 1;
  private Object obj = new Object();

  public void printEven() {
    while (true) {
      if (count > MAX)
        break;
      synchronized (obj) {
        System.err.println(Thread.currentThread().getName() + " : " + count++);
        obj.notify();
        try {
          obj.wait();
        } catch (InterruptedException e) {
        }
      }
    }
  }

  public void printOdd() {
    while (true) {
      if (count > MAX)
        break;
      synchronized (obj) {
        System.err.println(Thread.currentThread().getName() + " : " + count++);
        obj.notify();
        try {
          obj.wait();
        } catch (InterruptedException e) {
        }
      }
    }
  }
}

public class PrintEvenOddTester {
  public static void main(String[] args) {
    Print p = new Print();
    Thread t1 = new Thread(() -> p.printEven());
    t1.setName("EVEN");
    Thread t2 = new Thread(() -> p.printOdd());
    t2.setName("ODD");

    t1.start();
    t2.start();
  }
}

I wanted to check whether there is any better or efficient way to do these kind of tasks? I ran both the code and it works fine so wanted to check if everything looks good from thread safety and synchronization perspective.

Since in my above code, I am using while(true) loop which will take some CPU's so I am not sure whether this is the best way to do it?


texts:
This is one of the puzzles I was trying to solve, where the question is to validate the credit card number with following characteristics:

  It must contain exactly 16 digits.
  It must start with a 4,5 or 6
  It must only consist of digits (0-9).
  It may have digits in groups of 4 , separated by one hyphen "-".
  It must NOT use any other separator like ' ' , '_', etc.
  It must NOT have  4 or more consecutive repeated digits.

I have go through some of the solutions here and here as well, but the characteristics for validating are different from what I was working on, hence posting this.

total_count = int(raw_input())
numbers_list = []
#refernece list to check the starting series
start_list = [4,5,6]

for count in range(total_count):
    numbers_list.append(raw_input())

#condition 1, validates the starting series
def val_start(num):
    if int(num[0]) in start_list:
        return True
    else:
        return False

#to check if individial elements of the list are of length=4
#4321-5555-67899-9991, splitted to ["4321","5555","67899","991"] which is invalid
def val_group(num):
    for val in num.split("-"):
        if len(val) != 4:
            return False

    return True

#condition 2, validates the length of the number
def val_len(num):
    check = num
    check2 = True
    if "-" in num:
        check = "".join(num.split("-"))
        check2 = val_group(num)

    if ((len(check) == 16) and check2):
        return True
    else:
        return False

#condition 3, validates if input consists only number
def val_isdigit(num):
    if not num.isdigit():
        for ch in num:
            if not (ch.isdigit() | (ch == "-")):
                return False
    return True

#condition 4, validates the repetition of any number for 4 consective times
def val_rep(num):
    res = "".join(num.split("-"))
    for i in range(len(res)):
        try:
            if (res[i] == res[i+1]):
                if (res[i+1] == res[i+2]):
                    if (res[i+2] == res[i+3]):
                        return False
        except IndexError:
           pass
    return True

for num in numbers_list:
    #returns all the values into a list
    result = [val_start(num), val_len(num),val_isdigit(num), val_rep(num)]
    if False in result:
        print("Invalid")
    else:
        print("Valid")

I am looking for an optimised way for the function val_rep(), which validates the repetition of any number for 4 consecutive times.


texts: Accounts payable buckets (Current,30,44,48,60)

texts:
The following method is designed to display what we owe to a vendor based on 5 buckets. Basically, an aged trial balance (totals only). It also needs to be able to display the data based on any date. It shows me what the trial balance would have looked like on April 1st. By default it displays based on the date that it is run. The if and elif branching "smells".

def _get_balances(self,ref_date=None):
        if not ref_date:
            ref_date = datetime.date.today()
        totals = [Decimal('0.0'),Decimal('0.0'),Decimal('0.0'),Decimal('0.0'),Decimal('0.0')]
        for invoice in self.invoices:
            if invoice.date:
                payments = Decimal('0.0')
                for payment in invoice.payments:
                    if payment.check.date <= ref_date:
                        payments += payment.amount
                invoice_total = invoice.amount - payments
                if invoice.date >= ref_date - relativedelta(days=29):
                    totals[0] += invoice_total
                elif invoice.date <= ref_date - relativedelta(days=30) and \
                    invoice.date >= ref_date - relativedelta(days=43):
                        totals[1] += invoice_total
                elif invoice.date <= ref_date - relativedelta(days=44) and \
                    invoice.date >= ref_date - relativedelta(days=47):
                        totals[2] += invoice_total
                elif invoice.date <= ref_date - relativedelta(days=48) and \
                    invoice.date >= ref_date - relativedelta(days=59):
                        totals[3] += invoice_total
                elif invoice.date <= ref_date - relativedelta(days=60):
                    totals[4] += invoice_total
        return tuple(totals)


texts:
This JavaScript object is part of a mobile application that rolls dice for our D&D games.

Here are some example of possible inputs from the user:

2d4
2d4 + 3d6
2d4 + 3d6 + 12

function DiceRoller() {
    this.rollDices = function(input){

        var parsedInput = input.split("+");
        var totalScore = 0;

        for (var diceIndex = 0; diceIndex < parsedInput.length; diceIndex++) {

            var diceRoll = parsedInput[diceIndex];

            //If we can't find 'd', it means we only have to add the input
            if (diceRoll.indexOf("d") > 0) {
                var diceParts = diceRoll.split('d');

                //We need a random roll for each dice. ex: 4d6, needs 4 rolls.
                for (var numberOfDiceIndex = 0; numberOfDiceIndex < diceParts[0];numberOfDiceIndex++) {
                    totalScore += getRandomInt(1,diceParts[1]);
                }
            } else {
                totalScore += parseInt(diceRoll);
            }
        }

        return totalScore;
    };

    var getRandomInt = function(min, max){
        return Math.floor(Math.random()*(max-min+1)+min);
    }
}

I'm concerned about the performance of the rollDices method, considering I use split quite a lot and I have nested loops.


texts:
I've decided to make an implementation of the C++11 class function. I was checking that I have done everything correctly and have not missed anything:

template < typename > class function;

template < typename _Ret, typename... _Args > class function<_Ret(_Args...)>
{
public:
    typedef _Ret result_type;
    typedef function<result_type(_Args...)> _Myt;
    typedef result_type(*pointer)(_Args...);

    function()
        : _f_ptr(nullptr)
    {
    }

    template < typename _Fn_Ty > function(_Fn_Ty &&_Fn)
        : _f_ptr(reinterpret_cast<pointer>(_Fn))
    {
    }

    function(pointer &&_Fn)
        : _f_ptr(_Fn)
    {
    }

    function(const _Myt &_Rhs)
        : _f_ptr(_Rhs.f_ptr)
    {
    }

    function(_Myt &&_Rhs)
        : _f_ptr(_Rhs.f_ptr)
    {
    }

    ~function()
    {
    }

    _Myt &assign(pointer &&_Fn)
    {
        _f_ptr = _Fn;
        return *this;
    }

    _Myt &operator=(pointer &&_Fn)
    {
        return assign(_Fn);
    }

    template < typename _Fn_Ty > _Myt &assign(_Fn_Ty &&_Fn)
    {
        _f_ptr = reinterpret_cast<pointer>(_Fn);
        return *this;
    }

    template < typename _Fn_Ty > _Myt &operator=(_Fn_Ty &&_Fn)
    {
        return assign<_Fn_Ty>(_Fn);
    }

    result_type operator()(_Args... _Arguments)
    {
        if (_f_ptr == nullptr)
        {
            throw std::exception("nullptr found instead of function");
        }
        return _f_ptr(_Arguments...);
    }

    pointer &ptr() const
    {
        return _f_ptr;
    }

    operator pointer &() const
{
    return _f_ptr;
}
private:
    pointer _f_ptr;
};


texts: Passing a 1D array (single column of a Range object) to .NET to manipulate it without loops and returning it back to VBA

texts:
Background

Kind of a follow up - slightly related to my other SO question.

I thought that if somehow I find a way in VBA to pass a single column to .NET and convert it to a native .NET type then I could finally overcome the mystery of explicitly looping on objects via COM (which is super slow as we all know). I'd then be able to use all the cool stuff and not worry about constantly looping through Excel.Range object.

Please note: this is all about a single column not an object[,].

VBA side of things

It turns out in VBA you can get a 1D array like this:

.NET Compatibility

Sample .tlb/.dll library in C# - click here to get an idea

It comes down to one method really:

public object Deduplicate1DArray(object arr)
{
    Array column = (Array)arr; // converts assumed/expected 1d array to System.Array
    List<string> list = column.OfType<string>().ToList(); // generic list to use the cool stuff
    column = list.Distinct<string>().ToArray(); // convert back to match the type
    return column;
}

So from all the research I have done I thought that passing the 1d from VBA to .NET as object type is the way to go. If you know/experienced a better way (like passing the Excel.Range please share).

A successful conversion to a native .NET System.Array is possible which is just sweet because an Array can easily be converted to a generic List<string> which gives me access to all the cool stuff.

So at this point I am not relying any longer on VBA to manipulate that Range and I can do amazing things that .NET allows me to on a generic List<T> type - I mean, how cool's that?

Testing...

Attached references in the VBE to my .tlb and now I am able to use my library like

Dim c as new COMClass

Currently, I can test it like this:

Sub Main()

    Cells.ClearContents

    [A1] = "foo"
    [A2] = "boo"
    [A3] = "doo"
    [A4] = "goo"
    [A5] = "foo"

    Dim arr1D As Variant
    arr1D = Application.Transpose(Range("A1:A5"))

    Dim c As New COMClass

    Dim noDuplicates As Variant
    noDuplicates = c.Deduplicate1DArray(arr1D)

    Range("B1").Resize(UBound(noDuplicates) + 1, 1) = Application.Transpose(noDuplicates)

End Sub

or

noDuplicates = Application.Transpose(c.Deduplicate1DArray(arr1D))
Range("B1").Resize(UBound(noDuplicates), 1) = noDuplicates

and that works as expected (either way)

What bothers me...

A user of the library has to know and remember that the COMClass.Deduplicate1DArray needs to be passed a 1d array... therefore, in VBA they have to call the Application.Transpose() on the Range object to pass it properly. Things can get very .Net'ish if the user decides to do things like:

noDuplicates = Application.Transpose(c.Deduplicate1DArray(Application.Transpose(Range("A1:A5"))))

or even worse

Range("B1").Resize(SOME_BIG_NUMBER, 1) = Application.Transpose(c.Deduplicate1DArray(Application.Transpose(Range("A1:A5"))))

Anything I could do in either VBA or C# to improve that? Creating another wrapper or maybe just accepting the Excel.Range object and try to break it down to a 1d array in .NET?
This:

Range("B1").Resize(10, 1) = c.Deduplicate1DArray(Range("A1:A5").Value)

would have been kind of good or at least look sensible in terms of syntax but the problem is I shouldn't be .Resizing my B1 - (destination) because I don't know how big the returned array after deduplication is going to be.

Any ideas of improving this are very welcome and if I have missed something please let me know I'll update with as much detail as I can.


texts: Extracting and cleaning up duplicate emails

texts:
Right now I am using a regex to extract emails from a text document, and filter the duplicates out of this using the Distinct function from linq. After which I run the output file through a clean up of duplicates as well, as the program can be run several times over several different files.

Now my question, would there be a more optimal way of checking the output file for duplicates? Because as it is right now, the bigger the file, the longer it will take.

And I have the feeling there should be a less intense way to check this.

// Extractor
public void Mail(string file)
{
    string strRegex = @"[A-Za-z0-9_\-\+]+@[A-Za-z0-9\-]+\.([A-Za-z]{2,3})(?:\.[a-z]{2})?";
    var myRegex = new Regex(strRegex, RegexOptions.None);

    var matches = new List<string>();
    foreach (Match myMatch in myRegex.Matches(file))
    {
        if (myMatch.Success)
        {
            matches.Add(myMatch.Value);
        }
    }

    var cleanMatch = matches.Distinct().ToList();

    for (var i = 0; i < cleanMatch.Count; i++)
    {
        Log.Mail(cleanMatch[i]);
    }

    CleanDuplicates();
}

// Duplicate Cleaner
private void CleanDuplicates()
{
    var lines = new List<string>(System.IO.File.ReadAllLines(System.Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory) + "\\EmailList.txt"));

    lines = lines.Distinct().ToList();
    string target = System.Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory) + "\\EmailList.txt";
    using (System.IO.StreamWriter newTask = new System.IO.StreamWriter(target, false))
    {
        for (var i = 0; i < lines.Count; i++)
        {
            newTask.WriteLine(lines[i]);
        }
    }
}


texts:
I have the following as my Ajax / PHP contact form on a site I am building.  I have sanitized the inputs but just wanted to make sure I havent missed anything...

    // Only process POST reqeusts.
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Get the form fields and remove whitespace.
        $name = strip_tags(trim($_POST["name"]));
        $name = str_replace(array("\r","\n"),array(" "," "),$name);
        $phone = trim($_POST["phone"]);
        $phone = filter_var($phone, FILTER_SANITIZE_NUMBER_INT);
        $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
        $subject = strip_tags(trim($_POST["subject"]));
        $subject = str_replace(array("\r","\n"),array(" "," "),$subject);
        $message = strip_tags(trim($_POST["message"]));
        $message = str_replace(array("\r","\n"),array(" "," "),$message);

        // Check that data was sent to the mailer.
        if ( empty($name) OR empty($phone)) {
            // Set a 400 (bad request) response code and exit.
            http_response_code(400);
            echo "Oops! There was a problem with your submission. Please complete the form and try again.";
            exit;
        }

        // Set the recipient email address.
        $recipient = "email@domain.com";

        // Set the email subject.
        $emailsubject = "New contact from $name";

        // Build the email content.
        $email_content = "Name: $name\n";
        $email_content .= "Email: $email\n\n";
        $email_content .= "Phone:\n$phone\n";
        $email_content .= "Subject:\n$subject\n";
        $email_content .= "Message:\n$message\n";

        // Build the email headers.
        $email_headers = "From: $name <$email>";

        // Send the email.
        if (mail($recipient, $emailsubject, $email_content, $email_headers)) {
            // Set a 200 (okay) response code.
            http_response_code(200);
            echo 'Thank You! Your message has been sent.';
        } else {
            // Set a 500 (internal server error) response code.
            http_response_code(500);
            echo "Oops! Something went wrong and we couldn't send your message.";
        }

    } else {
        // Not a POST request, set a 403 (forbidden) response code.
        http_response_code(403);
        echo "There was a problem with your submission, please try again.";
    }


texts:
This is a simple boilerplate / template for a bigger program (I hope), either linked to a DB or including a GUI frontend using PYQT or TKinter.

This is just a little tool I wrote to keep track of my own hours.

from datetime import datetime as dt

FMT = "%H:%M"
PARSE = (f"00:00", FMT)

class WorkingTime:
    def __init__(self, worker, company):
        self.worker = worker
        self.company = company
        # This can be a JSON file or a SQL DB
        self.days_dict = {
            "Monday": {"start": "", "end": ""},
            "Tuesday": {"start": "", "end": ""},
            "Wednesday": {"start": "", "end": ""},
            "Thursday": {"start": "", "end": ""},
            "Friday": {"start": "", "end": ""},
            "Saturday": {"start": "", "end": ""},
            "Sunday": {"start": "", "end": ""},
        }

    def set_start_hour(self, day, hour):
        self.days_dict[day.title()]["start"] = hour

    def set_end_hour(self, day, hour):
        self.days_dict[day.title()]["end"] = hour

    def set_start_and_end(self, day, start, end):
        self.days_dict[day.title()]["start"] = start
        self.days_dict[day.title()]["end"] = end

    def get_start_hour(self, day):
        return self.days_dict[day.title()]["start"]

    def get_end_hour(self, day):
        return self.days_dict[day.title()]["end"]

    def get_start_and_end(self, day):
        return self.days_dict[day.title()]["start"], self.days_dict[day.title()]["end"]

    def calculate_day_hours(self, hours):
        """ takes in a tuple and returns the number of hours"""
        start, end = hours
        try:
            start_time_obj = dt.strptime(f"{start[:2]}:{start[2:4]}", FMT)
            end_time_obj = dt.strptime(f"{end[:2]}:{end[2:4]}", FMT)
            return end_time_obj - start_time_obj
        except ValueError:
            return dt.strptime(*PARSE).strftime(FMT)

    def calculate_week_hours(self):
        """ returns the sum of the week """
        total = dt.strptime(*PARSE)
        for k, v in self.days_dict.items():
            if v.get("start") and v.get("end"):
                hours = self.calculate_day_hours((v.get("start"), v.get("end")))
                total += hours
        return total.strftime(FMT)

    def display_hours_day(self, day, hours):
        """ Returns a string of the hours for that day """
        day_hours = self.get_start_and_end(day)
        rtn_hours = self.calculate_day_hours(day_hours)
        space = " " * (11 - len(day))
        return f"\n\t{day.title()}{space}::  {rtn_hours} Hours\n"

    def display_hours_week(self):
        """ Returns a string of the hours for the week """
        rtn_str = "\n"
        rtn_str += f"\n\tName       ::  {self.worker}\n\tCompany    ::  {self.company}"
        line = "-" * 50
        total_line = '-'*26
        rtn_str += f"\n{line}"
        for k, v in self.days_dict.items():
            if v:
                hours = self.calculate_day_hours((v.get("start"), v.get("end")))
                rtn_str += self.display_hours_day(k, hours)
        total = self.calculate_week_hours()
        rtn_str += f"\t{total_line}"
        rtn_str += f"\n\tTotal      ::  {total} Hours\n"
        rtn_str += f"\n{line}\n\n"
        return rtn_str

wt = WorkingTime('Maffaz', 'IT Circle Consult')

# Set hours
wt.set_start_hour("monday", "0730")
wt.set_end_hour("monday", "1800")
wt.set_start_and_end("TUESDAY", "", "")
wt.set_start_and_end("wednesday", "", "")
wt.set_start_and_end("THUrsday", "", "")
wt.set_start_and_end("FrIDAY", "", "")

# # get hours
print(wt.get_start_hour("Monday"))
print(wt.get_end_hour("Wednesday"))
print(wt.get_start_and_end("Friday"))

# calculate day hours
print(wt.calculate_day_hours(wt.get_start_and_end("monday")))

# calculate week hours
week = wt.calculate_week_hours()
print(week)

# print day hours
tues_hours = wt.get_start_and_end("tuesday")
print(wt.display_hours_day("Tuesday", tues_hours))

# print week hours total
print(wt.display_hours_week())


texts: Create objects corresponding to whichever field has value from among a list of fields

texts:
I have to create a form, which enables users to move stock of items to different statuses. The form will show the current stock(quantity) in a given status and then 5 input fields corresponding to 5 statuses. The user can input into one or more fields as to the quantity that they want to be moved into the new status. Once the user submits the form, based on whether a field has value, I have to put an entry corresponding to that entry into a table which will store some common properties as well as the intended status and the quantity of each.

Consider the following scenario, if total stock in status Purchased is 100.

Production  - 30
Finished - 20
Finished (Internal Only)
Wastage
Base Stock - 50

I will need to create 3 entries corresponding to Production, Finished and Base Stock, respectively from a single object returned from the front end form.

The application is written in AngularJS and C# Web API. The following is what I have written so far. WStockStatus is a single object in which I capture the input values from front end as separate fields.

Does this follow best practices? Is there a better way to go about it?

public bool moveStock(WStockStatus fromStockStatus)
    {
    const int STATUS_BASE = 1;
    const int STATUS_FIN = 2;
    const int STATUS_FINI = 3;
    const int STATUS_WAST = 4;
    const int STATUS_PRGR = 5;
    StockStatus stockStatus = new StockStatus();
    stockStatus.date = fromStockStatus.date;
    stockStatus.location = fromStockStatus.location;
    if(fromStockStatus.qtyBase > 0)
    {
        stockStatus.quantityUOM = fromStockStatus.qtyBase;
        stockStatus.status = STATUS_BASE;
        createStockStatus(stockStatus);  //another function that creates individual entry for stock status
    }
    if(fromStockStatus.qtyFin > 0)
    {
        stockStatus.quantityUOM = fromStockStatus.qtyFin;
        stockStatus.status = STATUS_FIN;
        createStockStatus(stockStatus);
    }
    if(fromStockStatus.qtyFini > 0)
    {
        stockStatus.quantityUOM = fromStockStatus.qtyFini;
        stockStatus.status = STATUS_FINI;
        createStockStatus(stockStatus);
    }
    if(fromStockStatus.qtyWast > 0)
    {
        stockStatus.quantityUOM = fromStockStatus.qtyWast;
        stockStatus.status = STATUS_WAST;
        createStockStatus(stockStatus);
    }
    if(fromStockStatus.qtyPrgr > 0)
    {
        stockStatus.quantityUOM = fromStockStatus.qtyPrgr;
        stockStatus.status = STATUS_PRGR;
        createStockStatus(stockStatus);
    }
    return true;
}

    private void createStockStatus(StockStatus newObj)
    {
        if (newObj.isValid())
        {
            newObj.deleted = false;
            newObj.submittedId = null;
            UserPersonal user = context.UserPersonal.FirstOrDefault(u => u.email == currentUserEmail);
            newObj.setCreatedTimeStamp(user); //sets fields CreatedBy, ModifiedBy with value of user
            context.StockStatus.Add(newObj);
            context.SaveChanges();
        }
        return null;
    }


texts: Taking 2 command line inputs and verifying that they are integers, within the correct range of values

texts:
I'm taking 2 command line inputs, which have to be integers between 2 and 1,000,000. These two values are then passed into the getPrimes function, which is just a Sieve of Eratosthenes algorithm, printing all prime numbers within the range specified by the two inputs. The two inputs, n and k, must be positive integers, where n > k. How can I better optimise my approach to collecting these inputs and verifying them, to decrease execution time?

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#define MAXVALUE 1000000

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

    if (argc != 3){
        printf("Warning: Check number of arguments.\n");
        return 1;
    }

    int i, j;
    for (j = 1; j <= 2; j++){
        for (i = 0; argv[j][i] != '\0'; i++){
            if (!isdigit(argv[j][i])) {
                printf("Warning: Please enter a valid integer.\n");
                return 1;
            }
        }
    }

    int n = atoi(argv[2]), k = atoi(argv[1]);

    if (n > MAXVALUE || k == 1 || k >= n){
        printf("Warning: Bad input.\n");
        return 1;
    }

    // getPrimes(n, k);

    return 0;

}


texts:
Write a function that a receives file name and an integer N as arguments, that represent a binary file which contains N integers, which constitute a permutation. Return the number of cycles in the permutation.

Code

int countCyclesHelper(int* array, int N) {
  int i, first, current, temp, counter = 0;
  for (i = 0; i < N; i++) {
    first = i;
    current = first;
    while (1) {
      if (array[current] == -1) {
        break;
      }
      temp = array[current] - 1;
      array[current] = -1;
      current = temp;
      if (current == first) {
        counter++;
        break;
      }
    }
  }
  return counter;
}

int countCycles(char *name, int N) {
  char *buffer = (char*)malloc(N);
  int *array = (int*)malloc(N);
  int i, numberOfCycles;
  FILE *fp = fopen(name, "rb");
  fread(buffer, sizeof(buffer), 1, fp);
  for (i = 0; i < N; i++) {
    array[i] = buffer[i] - '0';
  }
  numberOfCycles = countCyclesHelper(array, N);
  free(buffer);
  free(array);
  fclose(fp);
  return numberOfCycles;
}

Example

Input (test.bin):

54321

Output:

3

Any review is appreciated.


texts: Return the last word of the url and capitalize the first letter

texts:
Can the below code be done in one line? Do you think it should or is it ok like this?

function() {
var str = {{Click URL}};
var str1 = str.split('/').pop();
  return str1.charAt(0).toUpperCase() + str1.slice(1);
}


texts:
I am adding some check box filters on a HTML table, based on whether a check box is checked or not, and I am toggling rows.  Is there anyway I could improve this code?  There is no issue with it at the moment I could think of e.g. performance wise, but maybe someone could help me with decreasing number of lines.

HTML

                <asp:CheckBox ID="cbIncludeOpen" runat="server" ClientIDMode="Static" Checked="true" onclick="RMToggle()" />
                <asp:CheckBox ID="cbIncludeNew" runat="server" ClientIDMode="Static" onclick="RMToggle()" />
                <asp:CheckBox ID="cbIncludeClosed" runat="server" ClientIDMode="Static" onclick="RMToggle()" />
                <asp:CheckBox ID="cbIncludeRejected" runat="server" ClientIDMode="Static" onclick="RMToggle()" />

JS

function RMToggle() {
    var o = $("#cbIncludeOpen").is(':checked');
    var n = $("#cbIncludeNew").is(':checked');
    var c = $("#cbIncludeClosed").is(':checked');
    var r = $("#cbIncludeRejected").is(':checked');

    if (o) { $('#table1 tr[data-id="Open"]').show(); }
    else { $('#table1 tr[data-id="Open"]').hide(); }

    if (n) { $('#table1 tr[data-id="New"]').show(); }
    else { $('#table1 tr[data-id="New"]').hide(); }

    if (c) { $('#table1 tr[data-id="Closed"]').show(); }
    else { $('#table1 tr[data-id="Closed"]').hide(); }

    if (r) { $('#table1 tr[data-id="Rejected"]').show(); }
    else { $('#table1 tr[data-id="Rejected"]').hide(); }
}


texts: View model using different datetime component

texts:
Any advice on how to make this code; cleaner, more effective, just overall better!
Program setup object that is coming from the database EF. It then maps the object to a view model and converts datetime to string and different datetime components.
//EF Data
            List<MeetingEvent> Meeting = new List<MeetingEvent>();
            Meeting.Add(new MeetingEvent() { MeetingId = 1, MeetingName= "A1",StartDateTime= new DateTime(2020, 1, 01),EndDateTime = new DateTime(2020, 1, 05) });
            Meeting.Add(new MeetingEvent() { MeetingId = 2, MeetingName = "A2", StartDateTime = new DateTime(2020, 2, 01), EndDateTime = new DateTime(2020, 2, 05) });
            Meeting.Add(new MeetingEvent() { MeetingId = 3, MeetingName = "A3", StartDateTime = new DateTime(2020, 3, 01), EndDateTime = new DateTime(2020, 3, 05) });
            Meeting.Add(new MeetingEvent() { MeetingId = 4, MeetingName = "A4", StartDateTime = new DateTime(2020, 4, 01), EndDateTime = new DateTime(2020, 4, 05) });
            Meeting.Add(new MeetingEvent() { MeetingId = 5, MeetingName = "A5", StartDateTime = new DateTime(2020, 5, 01), EndDateTime = new DateTime(2020, 5, 05) });
//Logic
            var listOfEvents = Meeting.Select(x => new MeetingEventViewModel
            {
                MeetingId = x.MeetingId,
                MeetingName = x.MeetingName,
                StartDateTime = x.StartDateTime,
                EndDateTime = x.EndDateTime,
                StartDateDayName = x.StartDateTime.DayOfWeek.ToString(),
                StartDateMonth = x.StartDateTime.Month.ToString(),
                StartDateDay = x.StartDateTime.Day.ToString(),
                StartDateYear = x.StartDateTime.Year.ToString(),
                EndDateDayName = x.EndDateTime.DayOfWeek.ToString(),
                EndDateMonth = x.EndDateTime.Month.ToString(),
                EndDateDay = x.EndDateTime.Day.ToString(),
                EndDateYear = x.EndDateTime.Year.ToString(),
            }).ToList().OrderBy(o => o.StartDateTime);

            foreach (MeetingEventViewModel m in listOfEvents)
            {
                Console.WriteLine(m.MeetingId);
            }

    class MeetingEvent
    {
        public int MeetingId { get; set; }
        public string MeetingName { get; set; }
        public DateTime StartDateTime{ get; set; }
        public DateTime EndDateTime { get; set; }
    }

    class MeetingEventViewModel
    {
        public int MeetingId { get; set; }
        public string MeetingName { get; set; }
        public DateTime StartDateTime { get; set; }
        public DateTime EndDateTime { get; set; }
        public string StartDateDayName { get; set; }
        public string StartDateDay { get; set; }
        public string StartDateYear { get; set; }
        public string StartDateMonth { get; set; }
        public string EndDateDayName { get; set; }
        public string EndDateDay { get; set; }
        public string EndDateYear { get; set; }
        public string EndDateMonth { get; set; }

}


texts:
Whenever I create a Javascript "class" I do something like this:

// Definition
function MyObject() {
   this.id = 0;
   this.legs = 2;
}
MyObject.prototype = {
   walk: function() {
      // Do stepping
   },
   stop: function() {
      // Stop stepping
   }
};

// Instanciation
var TestMyObject = new MyObject();
TestMyObject.id = 1;
TestMyObject.legs = 3;

However, as I was trying to find a way to do fixed time step timers, I found another way to construct objects by passing in a key value pair object.  That got me thinking that it could be convenient to construct MY objects in a similar fashion.  So is there a problem with creating an object like this:

// Definition
function MyObject(objectSettings) {
   // Essentially acts as default constructor
   objectSettings = objectSettings || {};

   // Without a given parameter, use default
   this.id = objectSettings.id || 0;
   this.legs = objectSettings.legs || 2;

   // Make sure the reference is gone
   objectSettings = null; // Do I even need this?
}
MyObject.prototype = {
   walk: function() {
   },
   stop: function() {
   }
};

// Instanciation

// Use all defaults
var TestMyObject01 = new MyObject();

// Set only id
var TestMyObject02 = new MyObject({
   id: 1
});

// Set everything
var TestMyObject02 = new MyObject({
   id: 1,
   legs: 3
});

My question is, objectSettings doesn't stick around after instantiating the new object right?  Maybe I'm being paranoid.  I'm still trying to wrap my head around closures and initially I had a var inside the definition that referenced the passed objectSettings but I figured that was a bad choice because that would be a private immutable reference to a hunk of memory that was just used to copy into an object and that memory wouldn't go away as long as the created object was around.

I realize it would probably be even easier to pass values in individually to the constructor, but I thought maybe this would be a way to overcome the limitation of not being able to overload a function based on parameter type.  I would pass what I want to set specifically and if it isn't in the passed object (or if there is no passed object at all) the parameter would be set to a default value.  Is there a better way to construct objects in a similar fashion?

I can't find the link to the timer object that got me on this but If I do find it, I'll link it here.


texts: Return Set with random unique Integer numbers between min and max range

texts:
I need set of random unique Integer numbers for my unit test. I implemented this method, however I'm not sure if this is best way to implement this.

private Set<Integer> getRandomUniqueNumberSet(Integer min, Integer max)
{
    Set<Integer> added = new LinkedHashSet<Integer>();
    for(int i = min; i <= max; i++)
    {
        Integer index = ThreadLocalRandom.current().nextInt(min, max + 1);
        Boolean loop = false;
        if(!added.add(index)) loop = true;
        while(loop)
        {
            index = ThreadLocalRandom.current().nextInt(min, max + 1);
            if(added.add(index)) loop = false;
        }
    }
    return added;
}

Example:

for(Integer index : getRandomUniqueNumberSet(2, 15))
{
    System.out.println("Index: " + index);
}

Results:

Index: 8
Index: 5
Index: 15
Index: 9
Index: 4
Index: 3
Index: 7
Index: 2
Index: 11
Index: 14
Index: 6
Index: 10
Index: 13
Index: 12


texts: Typesafe scanf-like function with variadic templates

texts:
I'm hoping to get some feedback on a function with variadic templates that parses a format string and fills in some parameters whose order and types are based on the characters in the format string. Kind of like scanf().

(For the curious, I am trying to make a typesafe version of this function, documentation here.)

I'm pretty experienced with C but the last time I did anything serious with C++ was at university 15 years ago and it seems like a completely different language now.

This toy code works for me and fails in the ways I'd expect it to when I give it bad input. However, I'm not too familiar with the standard library so I have a strong feeling that I may be missing something. Also the code seems overly verbose for what it does.

So here's what I'm hoping to find out:

Is this code idiomatic modern C++?
Am I overlooking useful features in the standard library that would make things easier?
Should I be using pointers in this way, or am I thinking too much in C?
Should I consider another approach entirely, like tscanf(format, paramname1, paramname2) >> param1 >> param2?

I am constrained to use C++11, the code currently does not use Boost.

#include <cstring>
#include <iostream>

struct SomeStruct {
    int val;
};

template<typename T>
bool
assign(const char c, T& ref) {
    return false;
}

template<>
bool
assign(const char c, bool*& ref) {
    if (c != 'b')
        return false;
    *ref = true;
    return true;
}

template<>
bool
assign(const char c, int*& ref) {
    if (c != 'i')
        return false;
    *ref = 42;
    return true;
}

template<>
bool
assign(const char c, SomeStruct& ref) {
    if (c != 'h')
        return false;
    ref.val = 81;
    return true;
}

template<typename T>
bool
tscanf(const char *format, const char *name, T& ref)
{
    if (std::strlen(format) != 1) {
        std::cerr << "Wrong number of arguments" << std::endl;
        return false;
    }

    if (!assign(format[0], ref)) {
        std::cerr << "Wrong type for argument " << name << std::endl;
        return false;
    }

    return true;
}

template<typename T, typename... Args>
bool
tscanf(const char *format, const char *name, T& ref, Args... args)
{
    if (!assign(format[0], ref)) {
        std::cerr << "Wrong type for argument " << name << std::endl;
        return false;
    }

    return tscanf(format + 1, args...);
}

int
main(void)
{
    bool b;
    int i;
    SomeStruct h;
    if (!tscanf("hbi",
        "handle", h,
        "switch", &b,
        "num", &i))
        return 1;
    std::cout << h.val << ' ' << b  << ' ' << i << std::endl;
    return 0;
}


texts:
I wrote this quicksort implementation in C++

#include <iostream>
#include <vector>
#include <algorithm>
#include <cassert>

void myquicksort(std::vector<int>& A, const int left, const int right)
{
  int i = left;
  int j = right;
  int pivot = A[left + ((right - left) / 2)];

  while(i < j)
  {
    while(A[i] < pivot) ++i;
    while(A[j] > pivot) --j;

    if(i <= j)
    {
      std::swap(A[i], A[j]);
      ++i;
      --j;
    }
  }

  if(left < j) myquicksort(A, left, j);
  if(i < right) myquicksort(A, i, right);
}

void quick_sort(std::vector<int>& A)
{
  myquicksort(A, 0, A.size() - 1);
}

int main()
{
  std::vector<int> v{8, 37, 4, 12, 1, 19, 13, 6, 23, 42, 3};
  auto v2 = v;
  quick_sort(v);
  std::sort(v2.begin(), v2.end());
  assert(v2 == v);
}

Can you share your opinions?

One remark: I am curious about times where i == j on some occasions in those lines:

  if(left < j) myquicksort(A, left, j);
  if(i < right) myquicksort(A, i, right);

therefore calling myquicksort with overlapping ranges. Is that an issue?


texts:
Using Advent of Code as a source of toy problems for my first dabblings in Rust. Looking for feedback from more-seasoned Rustaceans on usage of the language.

Advent of Code Day 1: Inverse Captcha

use std::fs::File;
use std::io::prelude::*;

fn get_input() -> Vec<u8> {
    let mut file = File::open("input.txt").unwrap();
    let mut content = Vec::new();

    file.read_to_end(&mut content).unwrap();
    for i in 0 .. content.len() {
        content[i] = content[i] - ('0' as u8);
    }

    content
}

fn offset_sum(input: &[u8], offset: usize) -> i32 {
    let len = input.len();
    let mut sum = 0;

    for i in 0 .. len {
        let j = (i + offset) % len;
        if input[i] == input[j] {
            sum += input[i] as i32;
        }
    }

    sum
}

fn main() {
    let input = get_input();

    println!("Part 1 total: {}", offset_sum(&input, 1));
    println!("Part 2 total: {}", offset_sum(&input, input.len()/2));
}


texts: What might be another way to test if int is 32 bits wide at compile time?

texts:
Below is code that will compile when INT_MAX is equal to 232. It will generate a compiler error when INT_MAX is not equal to 232.

#include <iostream>
#include <climits>

namespace NBitCheck
{
    template<bool> struct CTAssert;
    template<> struct CTAssert<true> {};

    constexpr bool intbitwidthcheck=INT_MAX-(2^32)+1;
    CTAssert<intbitwidthcheck> a;
}

int main(void) {

  return 0;
}


texts: Check the response of an API for correctness

texts:
I expecting the response of an API to be a array of objects like this:

[
    {
        "code": "X",
        "name": "Product A",
        "pricings": []
    },
    {
        "code": "Y",
        "name": "Product B",
        "pricings": []
    },
    {
        "code": "Z",
        "name": "Product C",
        "pricings": []
    }
]

I want to check if the response actually looks like this, to sort out error's.

I did the following:

function checkResponseApi(response, mustHave) {
    if(Array.isArray(response)) {

        if(response.length === 0) {
            return false;
        }

        var success = response.every(obj => {
            var keys = Object.keys(obj);
            var output = mustHave.map(el => keys.includes(el));

            return output.indexOf(false) === -1;
        })

        return success;
    } else {
        return false;
    }
}

if (checkResponseApi(arr, ["code", "name", "pricings"])) {
    // continue
} else {
    // handle error
}

Is this a valid solution? Maybe you can share some experience and provide another/better approach.

Thanks in advance.


texts:
I would like to do the following:
I have a list data of 3-tuples that I need to go through, for each tuple base_tuple I want to know the index index_max of the maximum value held in base_tuple and replace base_tuple with a new 3-tuple new_tuple that only holds 0s except for the value at index index_max which is set at a fixed value fixed_value.
For instance, with a fixed_value of 127 and a base_tuple of (12, 55, 27), I expect new_tuple to be (0, 127, 0).

This is the code I use:

fixed_value = 255
# data is the list of tuples
for i, base_tuple in enumerate(data):
    index_max = base_tuple.index(max(base_tuple))
    new_tuple = tuple(fixed_value*(i==index_max) for i in range(3))
    data[i] = new_tuple

It works but it looks more like a hack than proper python... Any idea how to do this in a more pythonic way?


texts: Making my User model class code more modular, and correct

texts:
This is my first User model I created.

And I wanted to know if there are any good ways I can improve my code? It works with sessions, database and cookies.

I feel like some parts are somewhat written in a weird way, like in my constructor.

I would like to have my code as modular as possible, and maybe if there is anything to improve on when it comes to readability. It's understandable to me, because I wrote it, but it gets slightly complex.

class User
{
    private $db;
    private $req;
    private $data;

    public function __construct(Database $db, RequestHandler $req, $user = null)
    {
        $this->db  = $db;
        $this->req = $req;
        $sid       = $req->session('uid');
        $cHash     = $req->cookie('shash');

        if ($sid && !$user && !$cHash && !$this->data = $this->search($sid)) {
            # if only session user id is set AND user cannot be found

            unset($_SESSION['uid']);
        } elseif (!$sid && $user && !$this->data = $this->search($user)) {
            throw new Exception('User, ' . $user .  ', does not exist.');
        } elseif (!$sid && !$user && $cHash) {
            # if only shash (remember) cookie is present

            $sql  = 'SELECT * FROM sessions WHERE hash = ?';
            $data = $this->db->query($sql, $cHash);

            if ($data->rowCount() > 0) {
                $id = $_SESSION['uid'] = $data->fetch()->user_id;
                $this->data = $this->search($id);
            }
        }
    }

    public function create($fname, $lname, $email, $pw)
    {
        $sql = 'INSERT INTO users (firstname, lastname, email, password) VALUES(?, ?, ?, ?)';

        $this->db->query($sql, [$fname, $lname, $email, $pw]);
    }

    public function search($user)
    {
        $col  = is_numeric($user) ? 'id' : 'email';
        $sql  = 'SELECT * FROM users WHERE ' . $col . ' = ?';
        $data = $this->db->query($sql, $user);

        if ($data->rowCount() > 0) {
            return $data->fetch();
        }

        return false;
    }

    public function login($email, $pw, $remember = false)
    {
        if ($data = $this->search($email)) {
            $pwHasher = new PasswordHash(8, false);
            $pw       = $pwHasher->CheckPassword($pw, $data->password);

            if ($pw) {
                # user succussfully authenticated
                $this->data      = $data; //load data in entire class
                $_SESSION['uid'] = $data->id;

                if ($remember == true) {
                    $sql  = 'SELECT hash FROM sessions WHERE user_id = ?';
                    $data = $this->db->query($sql, $data->id);

                    if ($data->rowCount() === 0) {
                        $hash = CryptoCharGen::alnum(60);
                        $sql  = 'INSERT INTO sessions (user_id, hash) VALUES(?, ?)';

                        $this->db->query($sql, [$this->data->id, $hash]);

                        setcookie('shash', $hash, time() + 60 * 60 * 24 * 7);
                    }
                }

                return true;
            }
        }

        return false;
    }

    public function logout()
    {
        $sql = 'DELETE FROM sessions WHERE user_id = ?';

        $this->db->query($sql, $this->data->id);

        unset($_SESSION['uid']);

        setcookie('shash', '', time() - 1);

        session_regenerate_id(true);
    }

    public function getData()
    {
        return $this->data;
    }

    public function isLoggedIn()
    {
        return isset($this->data);
    }
}


texts: Ternary tree preoder traversal (recursive implementation)

texts:
Problem statement:

  Print out to console the ternary tree preorder traversal. Suppose that the tree can have at most 3 children, left, middle and right. Preorder traversal is to visit the middle child first, and then left, and then right. Every node has integer value.

My introduction of Algorithm

I was asked to write a simple recursive algorithm two years ago at the end of an important meeting. I like the algorithm, so I reviewed the algorithm and wrote a short C# solution today.

I am planning to study a few of short C# courses by myself on pluralsight.com called "defensive code in C#", "Code Contracts", "Provable Code", learn to write better C# code in next 2 weeks. I am learning C# right now.

I am trying to get some critics on my practice today.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TernaryTreePreorderTraversal
{
    class TernaryTree
    {
        static void Main(string[] args)
        {
            RunTestcase();
        }

        /*
         * Ternary tree:
         *      1
         *    / | \
         *   3  2  5
         *  /|  |
         * 4 33 22
         */
        public static void RunTestcase()
        {
            var root = new TernaryTree(1);

            root.Middle = new TernaryTree(2);
            root.Left   = new TernaryTree(3);
            root.Right  = new TernaryTree(4);

            root.Middle.Middle = new TernaryTree(22);
            root.Left.Middle   = new TernaryTree(33);
            root.Right = new TernaryTree(5);

            TernaryTree.PreOrderTraversal(root);

            // manually verify the console output is 1 2 22 3 33 4 5
        }

        public TernaryTree Left   { get; set; }
        public TernaryTree Right  { get; set; }
        public TernaryTree Middle { get; set; }
        public int Data { get; set; }

        public TernaryTree(int val)
        {
            Data = val;
        }

        public static void PreOrderTraversal(TernaryTree node)
        {
            if (node == null)
            {
                return;
            }

            Console.WriteLine(node.Data);

            PreOrderTraversal(node.Middle);
            PreOrderTraversal(node.Left);
            PreOrderTraversal(node.Right);
        }
    }
}


texts: Getting display size compact class in Android

texts:
I have written a common class for finding display sizes in pre-honeycomb and for the latest versions of Android. Could anyone review my code and suggest possible modifications for this code?

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Point;
import android.os.Build;
import android.view.Display;
import android.view.WindowManager;

public class DisplayManager {

    private Display mDisplay;
    private WindowManager mWindowManager;

    public DisplayManager(Context mContext) {
        mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        mDisplay = mWindowManager.getDefaultDisplay();
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    public int getDisplayHeight() {
        if (Integer.valueOf(android.os.Build.VERSION.SDK_INT) < 13) {
            return mDisplay.getHeight();
        } else {
            Point size = new Point();
            mDisplay.getSize(size);
            return size.y;
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    public int getDisplayWidth() {
        if (Integer.valueOf(android.os.Build.VERSION.SDK_INT) < 13) {
            return mDisplay.getWidth();
        } else {
            Point size = new Point();
            mDisplay.getSize(size);
            return size.x;
        }
    }
}


texts:
My question is more of a "can someone give me tips" rather than "can you do it for me"

I have been writing a C code implementation that takes a 32-char String in the form of binary (supposed to act as a 32-bit instruction) and divides it to four 8-char strings. Those four strings are converted to Hex and fed to a small code program that returns the Rijndael S-box Forward and Inverse equivalent.

When I showed the code to my supervisor, he asked me to optimize the code I have. Even though after many iterations of changing different parts of the code and reducing the performance time slightly, I do not have ideas of how to improve it. So, the code is below, and I would be grateful for any tips and suggestions of how I can improve the performance of the code below. (Also, if you could suggest how to improve the amount of memory the code is using, that would be fabulous as well.)

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

unsigned char mulinv(unsigned char in) {
     //  multiplicative inverse in Rijndael's finite field.
    unsigned char k = 1, l = 1;
    //GF(2^8) = GF(2)[x]/(x8 + x4 + x3 + x + 1)
    //this takes the number of times I have to itterate in Rijndael's
    //finite field before I get my equivelant
    do {
        // equals k * 3
        k = k ^ (k << 1) ^ (k & 0x80 ? 0x1B : 0);
        // equals l / 3
        l ^= l << 1; l ^= l << 2; l ^= l << 4; l ^= l & 0x80 ? 0x09 : 0;
        } while (k != in);
        return l;
}

unsigned char makesbox(unsigned char in) {
        unsigned char s, x, l;
        l = mulinv(in);
        // affine transformation
        s = l ^ ((l << 1) | (l >> 7)) ^ ((l << 2) | (l >> 6)) ^ ((l << 3) | (l >> 5)) ^ ((l << 4) | (l >> 4));
        x = s ^ 0x63;
        return x;
}

unsigned char invsbox(unsigned char in) {
        unsigned char x;
         // affine transformation
        x = ((in << 1) | (in >> 7)) ^ ((in << 3) | (in >> 5)) ^ ((in << 6) | (in >> 2)) ^ 0x05;
        x = mulinv(x);
        return x;
}

void instSbox(unsigned char inst []) {
//        printf("Inst is : ");
        int i = 0;
//        for (i = 0; i < 32; i++){
//                printf("%c", inst[i]);
//        }
        unsigned char in[9];
        printf("\n---------------|Byte|SBox\n");
        for (i = 0; i < 33; i++){
                if (i%8 == 0 && i != 0) {
                        in[8] = '\0'; //NUL terminate the string.
                        unsigned char t = (unsigned char) strtol(in, NULL, 2);
                        printf("0x%X ", t);
                        printf("0x%X ", makesbox(t));
                        printf("0x%X \n", invsbox(t));
        }
        in[i%8] = inst[i];
        printf("%c ", in[i%8]);
    }
}

void main(){

    unsigned char inst [32] = "10101010101010101111111100111101"; // 32 bits (length of instructions)
    instSbox(inst);
}


texts: Class which encapsulates related socket streams

texts:
I have a class which encapsulates stream related objects, and I have provided the method API for doing basic manipulation on the stream read/write/close, but is this a good approach? The only benefit I can see is that if for some reason one wants to use other stream classes at a later point in the project, one can just replace the stream objects in the custom class, without touching the users of the stream, or create an interface for the users and another class which implements other stream objects. For my purposes I need stream objects which can read String messages, but maybe later would need to read byte chunks also.

public class MessageInputOutput {
    private PrintWriter writer;
    private BufferedReader reader;

    /**
     * Create an IO stream.
     * @param socketRef    Client socket reference.
     * @throws IOException
     */
    public MessageInputOutput(Socket socketRef) throws IOException {
        writer = new PrintWriter(new OutputStreamWriter(socketRef.getOutputStream()));
        reader = new BufferedReader(new InputStreamReader(socketRef.getInputStream()));
    }

    /**
     * Read message.
     * @return    Message string.
     * @throws IOException
     */
    public String readMessage() throws IOException {
        return reader.readLine();
    }

    /**
     * Write message
     * @param message    Message string.
     * @throws IOException
     */
    public void writeMessage(String message) throws IOException {
        writer.println(message);
        writer.flush();
    }

    /**
     * Close IO stream.
     * @throws IOException
     */
    public void closeMessageStream() throws IOException {
        writer.close();
        reader.close();
    }
}


texts: Calculate Cosine similarity between Multisets

texts:
Having read "Effective Java" and "Clean Code" I wanted to apply these principles in a manageable scenario. To this end I refactored a Java library that calculates similarities between strings.

The code below is that of a cosine metric. Documents are tokenized into multisets of strings. These are passed onto the metric which calculates their magnitude and dot product by treating the multisets as if they were (sparse) vectors.

package org.simmetrics.metrics;

import static com.google.common.collect.Multisets.union;
import static java.lang.Math.sqrt;

import org.simmetrics.MultisetMetric;

import com.google.common.collect.Multiset;

/**
 * Calculates the cosine similarity over two multisets. The similarity is
 * defined as the cosine of the angle between the multisets expressed as sparse
 * vectors.
 *

 *
 * similarity(a,b) = a·b / (||a|| * ||b||)
 *
 *
 *

 * The cosine similarity is identical to the Tanimoto coefficient, but unlike
 * Tanimoto the occurrence (cardinality) of an entry is taken into account. E.g.
 * {@code [hello, world]} and {@code [hello, world, hello, world]} would be
 * identical when compared with Tanimoto but are dissimilar when the cosine
 * similarity is used.
 *

 * This class is immutable and thread-safe.
 *
 * @see TanimotoCoefficient
 * @see Wikipedia
 *      Cosine similarity
 *
 * @param <T>
 *            type of the token
 */
public final class CosineSimilarity<T> implements MultisetMetric<T> {

    @Override
    public float compare(Multiset<T> a, Multiset<T> b) {

        if (a.isEmpty() && b.isEmpty()) {
            return 1.0f;
        }

        if (a.isEmpty() || b.isEmpty()) {
            return 0.0f;
        }

        float dotProduct = 0;
        float magnitudeA = 0;
        float magnitudeB = 0;

        // Lager set first for performance improvement.
        // See: MultisetUnionSize benchmark
        if(a.size() < b.size()){
            final Multiset<T> swap = a; a = b; b = swap;
        }

        for (T entry : union(a, b).elementSet()) {
            float aCount = a.count(entry);
            float bCount = b.count(entry);

            dotProduct += aCount * bCount;
            magnitudeA += aCount * aCount;
            magnitudeB += bCount * bCount;
        }

        //  a·b / (||a|| * ||b||)
        return (float) (dotProduct / (sqrt(magnitudeA) * sqrt(magnitudeB)));
    }

    @Override
    public String toString() {
        return "CosineSimilarity";
    }

}


texts: Dictionary load function using hash table

texts:
This loads a dictionary text file into memory to be used as part of a spell checker.  It's part of a larger program, but I wanted general comments so I can clean it up further.

#define TABLESIZE 500
#define LENGTH 45

bool load(const char* dictionary)
{
    //initiate hash table
    node* hashtable[TABLESIZE];

    //open dictionary and check
    FILE* dict = fopen(dictionary, "r");
    if (dict == NULL)
    {
        printf("Could not open file.");
        return false;
    }

    //initiate variable to store current word
    char* dword = calloc(LENGTH+ 1,sizeof(char));

    //read the file
    while(fscanf(dict, "%s", dword) != EOF)
    {
        //if there is a word, create node and put word in it
        node* new_node = malloc(sizeof(node));
        strcpy(new_node->word,dword);

        //find spot in hash table and put it in that bucket
        unsigned int hashkey= 0;
        for (int counter = 0; dword[counter]!= '\0'; counter++)
        {
            hashkey = (hashkey*dword[counter] + dword[counter] + counter)%TABLESIZE;
        }

        //check if spot in table exists; if not, start the linked list
        if (hashtable[hashkey] == NULL)
        {
            hashtable[hashkey] = new_node;
            new_node->next = NULL;
        }
        //otherwise made current node the first, shift rest over
        else
        {
            new_node->next = hashtable[hashkey];
            hashtable[hashkey] = new_node;
        }
        //count words for later use
        nwords++;

    }

    fclose(dict);
    return true;
}


texts:
Task is to encrypt part of the file using aes encryption algorithm. I did

public static byte[] AES_(int len, byte[] passwordBytes, byte[] saltBytes, FileStream fSin)
{

    byte[] encryptedBytes = null;
    byte[] encryptedBytesAndIV = null;

    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
    {
        using (AesCryptoServiceProvider AES = new AesCryptoServiceProvider())
        {
            AES.KeySize = 256;
            AES.BlockSize = 128;

            var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 100);
            AES.Key = key.GetBytes(AES.KeySize / 8);
            AES.IV = generateIV();

            AES.Mode = CipherMode.CBC;

            using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
            {
                byte[] buffer = new byte[1048576];
                int read,read2=0;

                while (read2 < len)
                {
                    read = fSin.Read(buffer, 0, buffer.Length);
                    cs.Write(buffer, 0, read);
                    read2 += read;
                }
                cs.Close();

            }
            encryptedBytes = ms.ToArray();
            encryptedBytesAndIV = new byte[encryptedBytes.Length + AES.IV.Length];
            AES.IV.CopyTo(encryptedBytesAndIV, 0);
            encryptedBytes.CopyTo(encryptedBytesAndIV, IV_LENGTH);
        }
    }

    return encryptedBytesAndIV;
}
private static byte[] generateIV()
{
    using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
    {
        byte[] nonce = new byte[IV_LENGTH];
        rng.GetBytes(nonce);
        return nonce;
    }
}

call function

  FileStream fsIn = new FileStream(path, FileMode.Open);
len = Convert.ToInt32(fsIn.Length) / 3;
 var resultb = AES_(len, passwordBytes, saltBytes, fsIn);

    fsIn.Seek(0, SeekOrigin.Begin);
    fsIn.Write(resultb, 0, resultb.Length);

    fsIn.Seek(fsIn.Length, SeekOrigin.Begin);
    fsIn.Write(saltBytes, 0, saltBytes.Length);
using (var writer = new BinaryWriter(fsIn))
{
    writer.Seek(Convert.ToInt32(fsIn.Length), SeekOrigin.Begin);
    writer.Write(resultb.Length);

}

The problem is that when a large file consumes a lot of memory and the computer freezes.Is it possible to alter this code so that the memory consumption of the PC was the minimum ?

As I understand it, that is the memory write bytes to the MemoryStream, but how different ? I need to overwrite the bytes in the same file if the same record byte immediately into a new file, it will have to write all the remaining bytes, and it is a waste of time and also memory


texts: Compiler for grond, a language-in-the-making

texts:
I'm working on a language called grond (see it on GitHub); the compiler is so small it is included in this post.

My gut tells me that this code is awful, but it works. I am hesitant to change things to make the code better because generally, I have found that bad things happen when I "fix" something that isn't necessarily broken.

How can I make this "ugly" code better? Note - If you don't think this code is ugly, please tell me!

String.prototype.reverse = function() {
  return this.split("").reverse().join("");
}

function replace(wc) {
  var lastWC;

  while (true) {
    lastWC = wc;
    wc = wc.reverse();
    wc = wc.replace("§", "");
    wc = wc.replace("Ś", "");
    wc = wc.replace(/\(a(?!\w)/, "(trela"); //alert ,a
    wc = wc.replace(/\(f(?!\w)/, "(rof"); // for, f
    wc = wc.replace(/\(w(?!\w)/, "(elihw"); //while,w
    wc = wc.replace(/\(p(?!\w)/, "(tpmorp"); //prompt,p
    wc = wc.replace(/\(vr\./, "(esrever."); //reverse, rv
    wc = wc.replace(/\(tm\./, "(chtam."); // match, mt
    wc = wc.replace(/\(nj\./, "(nioj."); //join, .jn
    wc = wc.replace(/\(pr\./, "(ecalper."); //replace, .rp
    wc = wc.replace(/\(ls\./, "(.ecils"); //slice, sl
    wc = wc.replace(/\(lt\./, "(esaCrewoLot."); //toLowerCase, tl
    wc = wc.replace(/\(ut\./, "(esaCreppUot."); //toUpperCase, tu
    wc = wc.replace(/\(ps\./, "(tilps."); //split, sp
    wc = wc.reverse();
    wc = wc.replace(/\.l(?!\w)/, ".length"); // .length, .l
    if (lastWC === wc)
      break;
  }
  return wc;
}

var source = prompt("Enter Source");
var sourceCopy = source;

var fullASCII = ' !#$%&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'.split('');
var y = (a) => {
  for (let char in fullASCII) {
    if (!source.contains(char)) {
      source.replace(a, char);
    }
  }
}
var OK = false;
var OK2 = false;
for (let char in fullASCII) {
  if (!source.contains(char)) {
    OK2 = OK ? true : false;
    OK = true;
  }
}
if (!OK2) {
  throw "Your program uses every ASCII charactor. Grond requires your program to leave 2 ASCII chars unused. This is stupid and will be fixed.";
}
y('\\\"');
y("\\\'");
var sourceSplit = sourceCopy.split("\'");
for (let i = 0; i < sourceSplit.length; i += 2) {
  var o = sourceSplit[i].split('\"');
  for (let e = 0; e < o.length; e += 2) {
    o[e] = replace(o[e]);
  }
  sourceSplit[i] = o.join('\"');
}
sourceCopy = sourceSplit.join("\'");

var append = "if(s != \"\"){alert(s)}";
var prepend = "var s = prompt();";
var oSS = source.split('');
if (oSS[0] == "§") {
  prepend = "var s = \"\"";
}
if (oSS[0] == "Ś" || oSS[1] == "Ś") {
  prepend = "with(math){" + prepend;
  append += "}";
}

sourceCopy = prepend + " String.prototype.la=function(h){var x=this.split(''); x[h] = x[h].toLowerCase(); return x.join('');};String.prototype.ca=function(h){var x=this.split(''); x[h] = x[h].toUpperCase(); return x.join('');};String.prototype.reverse=function(){return this.split('').reverse().join('');}; \n var h = ['hello, world', 'Hello, World', 'Hello, World!', 'hello, world!', 'hello world', 'hello world!', 'Hello World', 'Hello World!', 'Hello, world.', 'Hello, World.' ,'hello world.' , 'Hello World.'];  var q ='" + source + "'; " + sourceCopy + append;
alert(sourceCopy);
eval(sourceCopy);


texts: Displaying random elements for a quiz app

texts:
I'm a teacher and I built a one-page web app to display random question sets for quizzes and tests. The script I wrote selects one question from a set (array) of questions.

The script works fine, but I wonder if it follows best practices or if it could be made more efficient. I want to share my app with other teachers, but I don't want to spread bad practices.

Here's a fiddle of the app itself.

Clicking anywhere on the page brings up a spinner. Clicking again brings up five new random questions. There is more JS in the app, but I'm mainly concerned about the JS related to the question randomization.

// change questions here -- in quotes, comma separated
var qset1 = new Array("Set 1 Question 1","Set 1 Question 2","Set 1 Question 3","Set 1 Question 4","Set 1 Question 5");

var qset2 = new Array("Set 2 Question 1","Set 2 Question 2","Set 2 Question 3","Set 2 Question 4","Set 2 Question 5");

var qset3 = new Array("Set 3 Question 1","Set 3 Question 2","Set 3 Question 3","Set 3 Question 4","Set 3 Question 5");

var qset4 = new Array("Set 4 Question 1","Set 4 Question 2","Set 4 Question 4","Set 4 Question 4","Set 4 Question 5");

var qset5 = new Array("Set 5 Question 1","Set 5 Question 2","Set 5 Question 5","Set 5 Question 4","Set 5 Question 5");

function setUP() {
var set1=Math.floor(Math.random()*qset1.length);
var set2=Math.floor(Math.random()*qset2.length);
var set3=Math.floor(Math.random()*qset3.length);
var set4=Math.floor(Math.random()*qset4.length);
var set5=Math.floor(Math.random()*qset5.length);

document.getElementById('set_1').innerHTML = qset1[set1];
document.getElementById('set_2').innerHTML = qset2[set2];
document.getElementById('set_3').innerHTML = qset3[set3];
document.getElementById('set_4').innerHTML = qset4[set4];
document.getElementById('set_5').innerHTML = qset5[set5];

}


texts: determining if a range is within array of ranges

texts:
I have a List of a custom structure (myStruct) which has two ranges stored in it.
I'm trying to write a function where I can figure out if a range is completely enclosed in any of the ranges. Is this optimal and if not how can I improve it in terms of speed and memory efficiency?

class myStruct {
    private int start_one;
    private int stop_one;
    private int start_two;
    private int stop_two;

    public myStruct(int input_start_one, int input_stop_one, int input_start_two, int input_stop_two)
    {
        start_one = input_start_one;
        stop_one = input_stop_one;
        start_two = input_start_two;
        stop_two = input_stop_two;
    }
}

public void run()
{
    List<Struct> myStructs = new List<Struct>();
    myStructs.Add(new myStruct(86,724,725,1364));
    myStructs.Add(new myStruct(86,724,2068,2707));
    myStructs.Add(new myStruct(725,1364,2068,2707));

    if(is_in_range(88,100))
    {
        // in range
    }
}

public bool is_in_range(int in_start, int in_stop, BindingList<myStruct> input_list)
{
    myStruct current_item;
    for (int i = 0; i < input_list.Count; i++)
    {
        current_item = input_list[i];

        if (   (in_start >= current_item.start_one && in_stop <= current_item.stop_one)
            || (in_start >= current_item.start_two && in_stop <= current_item.stop_two))
                return true;
    }

    return false;
}