texts:
Left view of a Binary Tree is set of nodes visible when tree is visited from left side. Left view of following tree is 12, 10, 25.

       12

    /     \
 10       30
        /    \
      25      40

Looking for code review, optimizations and best practices. Also verifying space complexity is O(n) and not O(logn) where n is number of nodes in tree.

public class LeftView<T> {

    private TreeNode<T> root;

    /**
     * Takes in a BFS representation of a tree, and converts it into a tree.
     * here the left and right children of nodes are the (2*i + 1) and (2*i + 2)nd
     * positions respectively.
     *
     * @param items The items to be node values.
     */
    public LeftView(List<? extends T> items) {
        create(items);
    }

    private void create (List<? extends T> items) {
        root = new TreeNode<T>(null, items.get(0), null);

        final Queue<TreeNode<T>> queue = new LinkedList<TreeNode<T>>();
        queue.add(root);

        final int half = items.size() / 2;

        for (int i = 0; i < half; i++) {
            if (items.get(i) != null) {
                final TreeNode<T> current = queue.poll();
                final int left = 2 * i + 1;
                final int right = 2 * i + 2;

                if (items.get(left) != null) {
                    current.left = new TreeNode<T>(null, items.get(left), null);
                    queue.add(current.left);
                }
                if (right < items.size() && items.get(right) != null) {
                    current.right = new TreeNode<T>(null, items.get(right), null);
                    queue.add(current.right);
                }
            }
        }
    }

    private static class TreeNode<E> {
        TreeNode<E> left;
        E item;
        TreeNode<E> right;

        TreeNode(TreeNode<E> left, E item, TreeNode<E> right) {
            this.left = left;
            this.item = item;
            this.right = right;
        }
    }

    /**
     * Returns the left view of the binary tree
     *
     * @return  the left view of binary tree.
     */
    public List<T> leftView() {
        if (root == null) { throw new NoSuchElementException("The root is null"); }

        final List<T> leftView = new ArrayList<T>();
        computeLeftView(root, leftView, 1);
        return leftView;
    }

    private void computeLeftView(TreeNode<T> node, List<T> leftView, int currentDepth) {
        if (node != null) {
            if (currentDepth > leftView.size()) {
                leftView.add(node.item);
            }
            computeLeftView(node.left, leftView, currentDepth + 1);
            computeLeftView(node.right, leftView, currentDepth + 1);
        }
    }

    public static void main(String[] args) {
        final LeftView<Integer> leftView1 = new LeftView<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
        assertEquals(Arrays.asList(1, 2, 4)  , leftView1.leftView());

        final LeftView<Integer> leftView2 = new LeftView<Integer>(Arrays.asList(1, 2, 3, 4, null, 6, 7));
        assertEquals(Arrays.asList(1, 2, 4)  , leftView2.leftView());

        final LeftView<Integer> leftView3 = new LeftView<Integer>(Arrays.asList(1, 2, 3, null, 5, 6, 7));
        assertEquals(Arrays.asList(1, 2, 5)  , leftView3.leftView());

        final LeftView<Integer> leftView4 = new LeftView<Integer>(Arrays.asList(1, 2, 3, null, null, 6, 7));
        assertEquals(Arrays.asList(1, 2, 6)  , leftView4.leftView());
    }
}


texts:
I'm trying to parse an estimated travel duration and distance between two waypoints using Google Directions API. Tap on this to see an example of data received.

private class func parseTravelData(
    data: AnyObject!,
    mode: ESTMode,
    completion: (NSDictionary?) -> Void) {
        var receivedData = data as? NSDictionary

        if let routes = receivedData?["routes"] as? NSArray {
            if routes.count > 0 {
                if let legs = routes[0]["legs"] as? NSArray {
                    if legs.count > 0 {

                        var dur: String? = nil

                        if let duration = legs[0]["duration"] as? NSDictionary {
                            if let v = duration["value"] as? Float {
                                if v > ConnectionManager().timeMax && mode == .Walking {
                                    completion(nil) // resend using drive mode
                                }
                                else {
                                    if let t = duration["text"] as? String {
                                        dur = t
                                    }
                                }
                            }
                        }

                        if let d = dur {
                            if let distance = legs[0]["distance"] as? NSDictionary {
                                if let dist = distance["text"] as? String {
                                    completion([
                                        "duration": d,
                                        "distance": dist])
                                }
                            }
                        }
                    }
                }
            }
        }
}

This code works fine but looks awful. What I need is do nothing if data is incorrect. I can't come anything up with it. The main goal is avoiding of getting different unwrapping errors if something is wrong. I would greatly appreciate any help.


texts: Search GitHub users when text field changes in Kotlin Android app

texts:
Problem: Search for users by their name using the GitHub API (sorted by the number of followers) and display the results in a RecyclerView.

Implementation: Hitting the GitHub API every time when user type and calling the adapter to show the data.

 searchText.addTextChangedListener(object : TextWatcher {
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

            }

            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun afterTextChanged(s: Editable) {

                Log.v("Text is ",s.toString())

                val url="https://api.github.com/search/users?q="+s.toString().trim()+"+sort:followers"
                fetchData(url)
            }
        })

  private fun  fetchData(url: String) {

        val tag_string_req = "string_req"

        val strReq = StringRequest(Request.Method.GET,
                url, Response.Listener<String> {

                        response ->
                                Log.d(TAG, response.toString())

            val builder = GsonBuilder()
            val gson = builder.create()
            var allItems=gson.fromJson(response,AllUsers::class.java)

            Log.v("No of users",allItems.items?.size.toString())

            resultRecyclerView.adapter=adapter(this@MainActivity,allItems.items)

        }, Response.ErrorListener { error ->

            VolleyLog.d(TAG, "Error: " + error.message)

        })

// Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req)
    }

The code is working fine and giving the desired result.

Issues/point that I am thinking:

Here I am creating the new instance every time when user type. I think there should be the better way of doing this.

Edit: I came with this solution

In OnCreate()

 usersData= ArrayList()

        resultRecyclerView.setHasFixedSize(true)
        resultRecyclerView.layoutManager=LinearLayoutManager(this@MainActivity,LinearLayoutManager.VERTICAL,false)
        itemsAdapter=adapter(this@MainActivity,usersData)
        resultRecyclerView.adapter=itemsAdapter

in OnResume:

calling fetchData() as user typing.

private fun  fetchData(url: String) {

        val tag_string_req = "string_req"

        val strReq = StringRequest(Request.Method.GET,
                url, Response.Listener<String> {

                        response ->
                                Log.d(TAG, response.toString())

            val builder = GsonBuilder()
            val gson = builder.create()
            //val allItems=gson.fromJson(response,AllUsers::class.java)

            val data=gson.fromJson(response,AllUsers::class.java)
            usersData=data.items

            Log.v("No of users",usersData?.size.toString())

            resultRecyclerView.removeAllViews()
            itemsAdapter?.updateData(usersData)
            itemsAdapter?.notifyDataSetChanged()

        }, Response.ErrorListener { error ->

            VolleyLog.d(TAG, "Error: " + error.message)

        })

// Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req)
    }

In Adapter:

fun updateData(users: ArrayList<Items>?){
        this.users=users
    }


texts: shell library for Debian package releases

texts:
This is a bash library intended to be used in a CI/CD pipeline to make finding the next release number for a Debian package semi-automatic.  I figured out how to use a JSON file as a metadata store since the CI/CD pipeline I'm working with doesn't provide any metadata storage across jobs.

I'm basically happy with how this is working.  We've used it for a few weeks without finding any bugs yet.  I'm happy that it passes shellcheck, but I'd also like to have some linting for ensuring that the code is documented adequately.  I'm not sure if my use of jq makes this too hard to maintain or if it just that using jq like this is so new to me.

deblib.sh

#!/bin/bash

# TODO: generate $PKGJSON from Debian repo metadata
PKGJSON=/opt/org_foo/var/packaging/packaging.json

# deb-release-number
# ------------------
#
# Arguments:
# 1. (required) package name
# 2. (required) package version ("upstream" version)
# 3. (optional) architecture (defaults to amd64)
# 4. (optional) packager (defaults to 1org_foo)
#
# Testing:
# Test by running
#       bash deblib.sh debug
# or passing any argumenet in to activate the "verification" section below

function deb-release-number {
        # read arguments
        PKGNAME=${1?provide package name as first argument}
        PKGVER=${2?provide package version as second argument}
        PKGARCH=${3:-amd64}
        PACKAGER=${4-1org_foo}

        # find latest release of this package/version
        RELEASE=$(jq -r ".\"latest_version\".\"${PKGNAME}\".\"${PKGVER}\"" <"$PKGJSON" )
        if [[ "$RELEASE" == "null" ]];
        then
                # start at 0 so the first release ends up being 1 after the increment below
                RELEASE=0
        fi
        ## echo RELEASE=$RELEASE

        # increment
        RELEASE=$(( RELEASE + 1 ))
        LONGPKGVER="${PKGVER}-${PACKAGER}-${RELEASE}" # seperated with dashes
        PKGFILENAME="${PKGNAME}_${LONGPKGVER}_${PKGARCH}.deb" # seperated with underscores
        echo "new release $RELEASE of $PKGNAME creates filename $PKGFILENAME"

        # backup
        cp "$PKGJSON" "${PKGJSON}.bak"

        # update release_version (into tmp file)
        jq ".\"latest_version\".\"${PKGNAME}\".\"${PKGVER}\" = \"${RELEASE}\"" <"$PKGJSON" >"${PKGJSON}.tmp"
        ## grep "$PKGVER" "${PKGJSON}.tmp"

        # update built_packages (out of tmp file into main file)
        jq ".\"built_packages\" += [\"${PKGFILENAME}\"]" <"${PKGJSON}.tmp" >"$PKGJSON"
        ## grep "$PKGNAME" "$PKGJSON"

        return $RELEASE
}

# verification
if [[ $# -gt 0 ]];
then
        deb-release-number librdkafka1 1.0.0
        deb-release-number foo 1.1.0 noarch
fi

Example

An example of usage:

source deblib.sh
deb-release-number 'foo-stuff' "${GIT_TAG#v}" 'amd64'
PKGRELEASE=$?


texts: Searching for duplicates without any collection or sorting

texts:
I have written code which is easy to understand, but may not be efficient but will solve the purpose.

public static void main(String a[]){
        int ar[] ={1,2,3,4};
        boolean flag=false;
        int count=0;
        while(count<ar.length){
            for(int i=0;i<ar.length-1;i++){
                if(ar[count]==ar[i+1] && count !=i+1){
                    flag=true;
                }
        }
            count++;
        }
        if(flag){

        System.out.println("Duplicate Exists in Array!");
        }else{
            System.out.println("Duplicates Doesn't Exists in Array!");
        }

    }


texts: Build all possible phrase pairs from a sentence pair

texts:
I have an array for an English sentence (enSentence) and for a German sentence (deSentence). Each value represents one word. I want to print every possible phrase pair (enPhrase and dePhrase), where no phrase contains more than maxhPhraseLength words. A phrase can consist of a single word, all words of the sentence, and everything inbetween (consecutive).

So for Hello world ! and Hallo Welt !, possible phrase pairs would be:

Hello - Hallo
Hello world - Hallo
Hello world ! - Hallo
world - Hallo
world ! - Hallo
! - Hallo
…
Hello - Hallo Welt
Hello - Hallo Welt !
Hello - Welt
…
Hello world ! - Hallo Welt !

But phrases like Hello ! or world Hello are not possible.

This is my first try:

enLoop:
for(int en1 = 0; en1 < enSentence.length; en1++) {
  for(int en2 = en1; en2 < enSentence.length; en2++) {

    if(en2-en1+1 > maxPhraseLength) {
      continue enLoop;
    }

    deLoop:
    for(int de1 = 0; de1 < deSentence.length; de1++) {
       for(int de2 = de1; de2 < deSentence.length; de2++) {

         if(de2-de1+1 > maxPhraseLength) {
           continue deLoop;
         }

         // building the phrase pair
         enPhrase = "";
         dePhrase = "";
         for(int e = en1; e <= en2; e++) {
           enPhrase = enPhrase + " " + enSentence[e];
         }
         for(int d = de1; d <= de2; d++) {
           dePhrase = dePhrase + " " + deSentence[d];
         }
         enPhrase = enPhrase.trim();
         dePhrase = dePhrase.trim();
         System.out.println(enPhrase + " - " + dePhrase);

       }
     }

  }
}

I’m interested in any kind of feedback (I rarely create code from scratch).

I considered naming the variables language-neutral (in case I want to use the code for making phrase pairs in other languages, too), but couldn’t come up with something short and catchy (sourceSentence/source1 and targetSentence/target1 are longer, and I always have to remind myself what the source and what the target is, while it’s immediately clear to me if thinking about the terms en/English and de/German instead; but the difference doesn’t really matter in this case anyway).


texts:
This is my first Python web scraper (and overall my first Python project). I am also relatively new to OOP but do understand its core fundamentals. The script below scrapes two local news sites for their daily weather / allergy forecasts and converts it into an HTML file which opens locally in my browser. The file path also has a CSS file to style the output.

I know this code is not clean, and that it's not object oriented. Nothing is abstracted away into a function. I know that would be best practice, but I don't know enough to know how to clean it up. Any and all suggestions are very welcome.

import requests
from bs4 import BeautifulSoup
import urllib.request
from PIL import Image
import webbrowser, os

kxanUrl = 'https://www.kxan.com/weather/forecast/todays-forecast/'
kxanPage = requests.get(kxanUrl)
kvueUrl = 'https://www.kvue.com/allergy'
kvuePage = requests.get(kvueUrl)

soup = BeautifulSoup(kxanPage.content, 'html.parser')
weatherHtmlData = soup.find("div", {"class": "article-content rich-text"})
weatherText = weatherHtmlData.get_text()

tempHighHtml = soup.find('span', {"class": "high"})
tempHigh = tempHighHtml.get_text()

tempLowHtml = soup.find('span', {"class": "low"})
tempLow = tempLowHtml.get_text()

allergyImage = urllib.request.urlretrieve("http://cdn.tegna-media.com/kvue/weather/allergy16x9.jpg", "allergy_forecast.jpg")
image = Image.open("allergy_forecast.jpg")

template = """<!DOCTYPE html>

    <link rel="stylesheet" href="styles.css">
    <title>Daily Austin Forecast</title>

Weather Forecast

    Today's High: tempHigh    | Today's Low: tempLow

    FORECAST_INFORMATION

Allergy Forecast

"""
template = template.replace("FORECAST_INFORMATION", str(weatherText))
template = template.replace("tempHigh", str(tempHigh))
template = template.replace("tempLow", str(tempLow))

with open("forecast.html", "w") as file:
    file.write(template)

webbrowser.open('file://' + os.path.realpath("forecast.html"))
```


texts:
Follow-up from: Back to Basics - Tic Tac Toe

Again, any optimizations and critique is welcome! I'm particularly interested if it involves numpy, scipy | bitwise operators.

import numpy as np
from random import randint

def print_board(board):
    print("""
  +---+---+---+
c | {}   {}   {} |
  +   +   +   +
b | {}   {}   {} |
  +   +   +   +
a | {}   {}   {} |
  +---+---+---+
    1   2   3
""".format(*list(x if x != '0' else ' ' for x in board)))

def check_for_win(board):

    def check_diagonal(dia):
        return '0' not in dia and len(set(dia)) == 1

    a = np.array(board).reshape(3, 3)

    # check lr diagonal
    if check_diagonal(a.diagonal()):
        return True

    # check rl diagonal
    if check_diagonal(np.fliplr(a).diagonal()):
        return True

    # check rows & cols
    for matr in (a, np.transpose(a)):
        for row in matr:
            if '0' not in row and len(set(row)) == 1:
                return True

    return False

if __name__ == "__main__":
    board = ['0'] * 9
    codes = ('c1', 'c2', 'c3', 'b1', 'b2', 'b3', 'a1', 'a2', 'a3')
    turn, user = 1, 'X' if bool(randint(0, 1)) else 'O'
    print(f'Welcome! First to play is {user}!')
    print_board(board)

    while True:
        print(f'Player {user}: ')
        code = input().strip().lower()

        if code in codes:
            idx = codes.index(code)

            if board[idx] == '0':
                board[idx] = user
                print_board(board)

                if turn >= 5:
                    if check_for_win(board):
                        print(f'{user} won in {turn} turns! Congratulations!')
                        break
                    elif '0' not in board:
                        print("Aw, it's a draw!")
                        break

                user = 'X' if user == 'O' else 'O'
                turn = turn + 1
            else:
                print('Woops! You need to pick an empty space.')
        else:
            print("Hmm, that's not a valid input.")


texts: Validating ISBN-10s, with or without dashes in C++11

texts:
Description
A regex-based method of validating ISBN-10 as strings. Can be digits (or 'X' at the end) only, or with dashes, according to those of English-speaking publications (which are defined by the regular expressions contained in the code below).
The last digit, a check digit (unless it is an 'X'), is calculated in the following manner. Multiply each digit, starting from the leftmost digit, by a weight, and then sum the results. The check digit should be such that this sum is divisible by 11. The weight starts at 1, and increases by 1 for each digit. For example, consider the ISBN 0-306-40615-2. The sum is calculated as follows:
sum = 0*1 + 3*2 + 0*3 + 6*4 + 4*5 + 0*6 + 6*7 + 1*8 + 5*9 + 2*10 = 165
165 mod 11 = 0 // the check digit, 2, is valid.

I am a .NET developer dabbling in C++ for fun. With this exercise, I have tried to hide certain things from anything outside the namespace, by creating an anonymous namespace inside it. Essentially, I have tried to achieve what the private keyword does in C#, in C++ semantics. I am curious if I have done anything "un C++ like" in this code. I envisage this code could be expanded to have a function that validates ISBN-13 numbers.
Code
#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <algorithm>

namespace isbn_validation
{
    namespace // anonymous namespace
    {
        // regex expressions
        // dashless
        const std::regex isbn10_no_dashes(R"((\d{9})[\d|\X])");
        // with dashes
        const std::regex isbn10_dashes1(R"((\d{1})\-(\d{5})\-(\d{3})\-[\d|\X])");
        const std::regex isbn10_dashes2(R"((\d{1})\-(\d{3})\-(\d{5})\-[\d|\X])");
        const std::regex isbn10_dashes3(R"((\d{1})\-(\d{4})\-(\d{4})\-[\d|\X])");
        const std::regex isbn10_dashes4(R"((\d{1})\-(\d{5})\-(\d{3})\-[\d|\X])");
        const std::regex isbn10_dashes5(R"((\d{2})\-(\d{5})\-(\d{2})\-[\d|\X])");
        const std::regex isbn10_dashes6(R"((\d{1})\-(\d{6})\-(\d{2})\-[\d|\X])");
        const std::regex isbn10_dashes7(R"((\d{1})\-(\d{7})\-(\d{1})\-[\d|\X])");

        bool isbn10_check_digit_valid(std::string isbn10)
        {
            auto valid = false;

            // split it
            std::vector<char> split(isbn10.begin(), isbn10.end());

            // if the very last character is an 'X', don't bother with it
            if (split[9] == 'X')
            {
                return true;
            }

            // all digits
            // validate the last digit (check digit)
            int digit_sum = 0;
            int digit_index = 1;
            for (std::vector<char>::iterator it = split.begin(); it != split.end(); ++it)
            {
                digit_sum = digit_sum + ((*it - '0')*digit_index);

                digit_index++;
            }
            valid = !(digit_sum%11);

            return valid;
        }
    }

    bool valid_isbn10(std::string isbn)
    {
        // can take ISBN-10, with or without dashes
        auto valid = false;

        // check if it is a valid ISBN-10 without dashes
        if (std::regex_match(isbn, isbn10_no_dashes))
        {
            // validate the check digit
            valid = isbn10_check_digit_valid(isbn);
        }

        // check if it is a valid ISBN-10 with dashes
        if (std::regex_match(isbn, isbn10_dashes1) || std::regex_match(isbn, isbn10_dashes2) || std::regex_match(isbn, isbn10_dashes3) ||
            std::regex_match(isbn, isbn10_dashes4) || std::regex_match(isbn, isbn10_dashes5) || std::regex_match(isbn, isbn10_dashes6) || std::regex_match(isbn, isbn10_dashes7))
        {
            // remove the dashes
            isbn.erase(std::remove(isbn.begin(), isbn.end(), '-'), isbn.end());

            // validate the check digit
            valid = isbn10_check_digit_valid(isbn);
        }

        return valid;
    }
}


texts:
I recently made vim-dyon which is a syntax highlighter and indenter for the dyon programming language. There are probably some issues with being absolutely correct (since I am not too familiar with dyon), but it seems to do a good job in terms of how it works and looks. I am new to VimScript and I am looking for mostly a critique of my VimScript.

ftdetect/dyon.vim

autocmd BufNewFile,BufRead *.dyon setfiletype dyon

ftplugin/dyon.vim

if exists("b:did_ftplugin")
  finish
endif

let b:did_ftplugin = 1

setlocal tabstop=4
setlocal softtabstop=4
setlocal shiftwidth=4

indent/dyon.vim

if exists("b:did_indent")
  finish
endif
let b:did_indent = 1

if exists("*DyonIndent")
  finish
endif

" Dyon works similar to C, but without ;.
setlocal smartindent

syntax/dyon.vim

if exists("b:current_syntax")
    finish
endif

" Function/Closure
syntax keyword dyonKeyword fn grab

" Boolean
syntax keyword dyonKeyword true false

" Control keywords
syntax keyword dyonKeyword break continue else if for loop return in

" Special keywords
syntax keyword dyonKeyword mut go in any vec4

highlight link dyonKeyword Keyword

" Highlight functions
" (see: https://stackoverflow.com/a/45626295/667648)
syntax match dyonFunction "\zs\(\k\w*\)*\s*\ze("
highlight link dyonFunction Function

" Arithmetic operations

" a * b
syntax match dyonOperator "\v\*"
" a / b
syntax match dyonOperator "\v/"
" a % b
syntax match dyonOperator "\v\%"
" a + b
syntax match dyonOperator "\v\+"
" a - b
syntax match dyonOperator "\v-"
" a ^ b
syntax match dyonOperator "\v\^"
" a *= b
syntax match dyonOperator "\v\*\="
" a /= b
syntax match dyonOperator "\v/\="
" a %= b
syntax match dyonOperator "\v\%\="
" a += b
syntax match dyonOperator "\v\+\="
" a -= b
syntax match dyonOperator "\v-\="
" a ^= b
syntax match dyonOperator "\v\^\="
" a := b
syntax match dyonOperator "\v:\="

syntax match dyonOperator "\v[a-zA-z]+:"

" Boolean operations

" a && b
syntax match dyonOperator "\v\&\&"
" a and b
syntax match dyonOperator "\v and "
" a || b
syntax match dyonOperator "\v\|\|"
" a or b
syntax match dyonOperator "\v or "

highlight link dyonOperator Operator

" Numbers and strings
" (see
" https://github.com/pangloss/vim-javascript/blob/89fcb6bfcada1c4256284723778d128342b48350/syntax/javascript.vim#L57)
syntax match dyonString "\v#[0-9a-f]+"
syntax match dyonString /\c\<\%(\d\+\%(e[+-]\=\d\+\)\=\|0b[01]\+\|0o\o\+\|0x\x\+\)\>/
syntax region dyonString start=/\v"/ skip=/\v\\./ end=/\v"/
highlight link dyonString String

highlight link dyonNumber String

" Matches // style comment
syntax region dyonComment start="//" end="$"
highlight link dyonComment Comment

let b:current_syntax = "dyon"


texts: Implementing Luhn's algorithm to validate a credit card number in Java

texts:
I must implement Luhn's algorithm in a program to determine whether a given credit card number is valid or not, in addition I must print the name of the company that offers that credit card number. I believe this requires taking in the input as a string and converting each digit and testing if the number of digits in the input is in the valid range, which is 13 to 16.

I have paste my code below, would it be possible to have it reviewed and to receive feedback on whether or not my methods are correct and on issues such as how I may resolve my java.lang.NullPointerException. This would all help me continue in the right direction.

CreditCard.java

import java.util.Scanner;

public class CreditCard {

    private int evenSum;
    private int oddSum;
    private int sum;
    private String ccNumber;
    private String company;

    public boolean isDivisibleBy10() {
        return (getEvenSum() + getOddSum()) %10 == 0;
    }

    public boolean isValid() {
        return (validateNumber() && validateCompany());
    }

    public boolean validateCompany() {

        char[] ccArray = ccNumber.toCharArray();

        if(Character.getNumericValue(ccArray[0]) == 4) {
          company = "Visa";
          return true;
        }

        if(Character.getNumericValue(ccArray[0]) == 5) {
          company = "MasterCard";
          return true;
        }

        if(Character.getNumericValue(ccArray[0]) == 37) {
          company = "American Express";
          return true;
        }

        if(Character.getNumericValue(ccArray[0]) == 6) {
          company = "Discovery";
          return true;
        }
        return false;
      }

    public boolean validateLength() {
        String cardNumber = "";
        for (int  i = 0; i >= 16; i++){
          cardNumber += "1";
          while(i <= 16) {
            if (i >= 13) {
              System.out.println("valid length");
            } else {
              System.out.println("invalid length");
              break;
            }
          }
        }
        return false;
    }

    public boolean validateNumber() {
        // Luhn's algorithm
        long cardNumber = 0;
        long n = cardNumber;
        int sum = 0;
        int count = 0;

        while (n > 0)
        {
            int digit = (int)(n % 10);
            count++;
            if (count % 2 == 1){
                sum = sum + digit;
            }
            else if (digit<5){
                sum = sum + 2 * digit;
            }
            else{
                sum = sum + (2 * digit) - 9;
            }
            n = n/10;
        }
        return (sum % 10 == 0);
    }

    public boolean validateSums() {
        return isDivisibleBy10();
    }

    public CreditCard(String num) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter credit card number: ");
        num = input.nextLine();
        num = "0;";
    }

    public int getEvenSum() {
        return evenSum;
    }

    public int getOddSum() {
        return oddSum;
    }

    public int getSum() {
        sum = evenSum + oddSum;
        return sum;
    }

    public String getCcNumber() {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a number for a credit card number: ");
        ccNumber = input.nextLine();
        return ccNumber;
    }

    public String getCompany() {
        return company;
    }
}

tester.java

import java.util.Scanner;

        public class tester {

            public static void main(String[] args) {

                CreditCard cC = new CreditCard(null);

                System.out.print(cC.isValid());

            }
        }


texts:
I came through a question on Stack Overflow, which shows this array structure:

array (size=4)
  0 =>
    array (size=3)
      'id' => int 1
      'name' => string 'Anniversary' (length=11)
      'parent' => int 0
  1 =>
    array (size=3)
      'id' => int 12
      'name' => string 'New arrives' (length=11)
      'parent' => int 1
  2 =>
    array (size=3)
      'id' => int 13
      'name' => string 'Discount' (length=8)
      'parent' => int 12
  3 =>
    array (size=3)
      'id' => int 6
      'name' => string 'Birthday' (length=8)
      'parent' => int 0

and the required outcome needs to be the path for that list like shown below, implementation of adjacency list:

13 - Anniversary->New arrives->Discount
12 - Anniversary->New arrives
1 - Anniversary
6 - Birthday

I came to this solution:

$in = [
    ['id'=>1, 'name'=>'Anniversary', 'parent'=>0],
    ['id'=>12, 'name'=>'New arrives', 'parent'=>1],
    ['id'=>13, 'name'=>'Discount', 'parent'=>12 ],
    ['id'=>6, 'name'=>'Birthday', 'parent'=>0 ]
];

function path($element, $input) {
    $return = $input[ array_search($element, array_column($input, 'id')) ];
    $str [] = $return ['name'];
    if($return ['parent'] != 0) {
        $str [] = path($return ['parent'], $input);
    }
    return implode('->', array_reverse($str));
}

var_dump(path(13,$in));

It gets the task done, but I want to know if any improvements can be made to optimize the approach to the problem.


texts: Atmega328 watchdog, sleep and external interrupts

texts:
I have a customised Arduino board that will be connected to a battery and never power reset (it needs to be very reliable and cope with code hangs).

The board will always be put to sleep when not in use. I will use 2 external interrupts on pins D2 and D3 to wake up from sleep.

A watchdog is enabled to detect program lockups whilst not sleeping. This is disabled as this shouldn't be a problem when sleeping.

Below is the code: does it look ok?

#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>    // Needed to use interrupts

volatile int int0_flag;
volatile int int1_flag;

#define TRUE 1
#define FALSE 0

ISR(INT0_vect)
{
    int0_flag = TRUE;
}

ISR(INT1_vect)
{
    int1_flag = TRUE;
}

void sleepNow()
{
    wdt_disable();

    byte adcsra_save = ADCSRA;
    ADCSRA = 0;  // disable ADC
    power_all_disable ();   // turn off all modules
    set_sleep_mode (SLEEP_MODE_PWR_DOWN);   // sleep mode is set here

    noInterrupts();

    sleep_enable();

    interrupts();
    sleep_cpu ();            // now goes to Sleep and waits for the           interrupt
    sleep_disable ();      // precaution
    ADCSRA = adcsra_save;  // stop power reduction
    power_all_enable ();   // turn on all modules

    //enable watchdog to check for code lockups
    wdt_enable(WDTO_8S);
}   // end of sleepNow

void setup()
{
    Serial.begin(9600);
    Serial.println("starting...");

    pinMode(2, INPUT);
    pinMode(3, INPUT);

    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);

    EICRA = B00001010; // configure pin 2 and 3 for falling
    EIMSK = B00000011; // mask for INT1 and INT0

    int1_flag = FALSE;
    int0_flag = FALSE;

    wdt_enable(WDTO_8S);

    Serial.println("ready...");
}

void loop()
{
    if (int0_flag == TRUE)
    {
        Serial.println("wake up from INT0");
        int0_flag = FALSE;
    }
    if (int1_flag == TRUE)
    {
        Serial.println("wake up from INT1");
        int1_flag = FALSE;
    }

    Serial.println("1");
    delay(1000);
    Serial.println("2");
    delay(1000);
    Serial.println("3");
    delay(1000);
    sleepNow();
    //while (1)
}


texts: Animation that gets triggered by two buttons

texts:
In order for me to get better and create more desired code, I would like to find out if the following situation is bad or acceptable.

I am creating an animation that gets triggered by two buttons, one on the left of a JPanel and the other on the right. Depending on which button is pressed, the animation starts from the button position.

Now it can be quite some work working out the different calculations with a lot of internal if and else statements (to know which button is clicked) on the Method that handles the animation (I have done so).

If I clone the method and modify it to be suitable for one button (so each button calls a different method), which saves a lot of hassle, is that good or bad practise?

private void moveImage(){

    if(xpos < imagewidth && ypos < imageheight) {

           if(buttonA){

              image.setX(image.getX() - xmove);

           } else {

              image.setX(image.getX() + xmove);
           }

           image.setY(image.getY() + ymove);
    }

     //other codes here
}

Or I could do this for button A and the same for button B:

private void moveImageA(){

        if(xpos < imagewidth && ypos < imageheight) {

               image.setX(image.getX() - xmove);

               image.setY(image.getY() + ymove);
        }

          //other codes here
    }


texts: Project Euler Problem 3: Largest prime factor

texts:
The problem statement is as follows. I feel as if my code can be improved but I'm not able to see how to do so. Is there merit in removing {} on the if blocks? Since I'm new, could that unintentionally lead to bugs if I forget that only a single instruction can be executed?

The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(LargestPrimeFactor(600851475143));
        Console.ReadLine();
    }

    static long LargestPrimeFactor(long number)
    {
        long largestFactor = 1;

        for (long i = 2; i<= Math.Sqrt(number); i++)
        {
            if (IsFactorOf(number, i))
            {
                if (IsPrime(i))
                {
                    largestFactor = i;
                }

                while (number > 1 && IsFactorOf(number, i))
                {
                    number /= i;
                }
            }
        }

        if (number == 1)
        {
            return largestFactor;
        }
        else
        {
            return number;
        }

    }

    static bool IsFactorOf(long numerator, long denominator)
    {
        return numerator % denominator == 0 || numerator == denominator;
    }

    static bool IsPrime(long value)
    {
        int maxPossibleRoot = (int)Math.Sqrt(value);
        for (int i = 2; i <= maxPossibleRoot; i++)
        {
            if (value % i == 0)
            {
                return false;
            }
        }
        return true;
    }
}


texts: Making adding to a dictionary more efficient?

texts:
I have the following code and it's taking quite some time to run. I'm getting an Out of Memory Exception due to the high volume of answers there are.  Is there any way I could speed it up?

var controlStrings = answerControlStrings.Where(a => a.ControlN.Substring(a.ControlN.IndexOf('_') + 1, a.ControlN.Length - a.ControlN.IndexOf('_') - 1).Equals(newAnswer.QVar, StringComparison.InvariantCultureIgnoreCase));
if (controlStrings.Count() > 0)
{
    newAnswer.CatiControlStrings.Add("en", controlStrings.Where(c => c.CultureN.Contains("cati") && c.CultureN.Contains("en")).ToList());
    newAnswer.WebControlStrings.Add("en", controlStrings.Where(c => c.CultureN.Contains("web") && c.CultureN.Contains("en")).ToList());
    newAnswer.CatiControlStrings.Add("es", controlStrings.Where(c => c.CultureN.Contains("cati") && c.CultureN.Contains("es")).ToList());
    newAnswer.WebControlStrings.Add("es", controlStrings.Where(c => c.CultureN.Contains("web") && c.CultureN.Contains("es")).ToList());
}


texts: Balanced smileys check algorithm (part 2)

texts:
This is a follow-up for here.

  Problem

  Your friend John uses a lot of emoticons when you talk to him on
  Messenger. In addition to being a person who likes to express himself
  through emoticons, he hates unbalanced parenthesis so much that it
  makes him go :(

  Sometimes he puts emoticons within parentheses, and you find it hard
  to tell if a parenthesis really is a parenthesis or part of an
  emoticon.

  A message has balanced parentheses if it consists of one of the
  following:

  An empty string ""
  One or more of the following characters: 'a' to 'z', ' ' (a space) or ':' (a colon)
  An open parenthesis '(', followed by a message with balanced parentheses, followed by a close parenthesis ')'.
  A message with balanced parentheses followed by another message with balanced parentheses.
  A smiley face ":)" or a frowny face ":("
  Write a program that determines if there is a way to interpret his message while leaving the parentheses balanced.

I'm working on this balanced smileys checking algorithm, and my current solution is very naive, with just two rules:

At any point, the number of ) (close) should be less than the number of ( (open) + number of :( (frown)
At the end, the number of ( (open) should be less than the number of ) (close) and :) (smile)

I'm wondering if any bugs in my checking logic. Any advice on algorithm time complexity improvement or code style advice is highly appreciated as well.

def check_balance(source):
    left = 0
    right = 0
    frown = 0
    smile = 0
    for i,c in enumerate(source):
        if c == '(':
            left += 1
            if i > 0 and source[i-1] == ':': # :(
                left -= 1
                frown += 1
        elif c == ')':
            right += 1
            if i > 0 and source[i-1] == ':': # :)
                right -= 1
                smile += 1
                if left + frown < right:
                    return False
    if left > right + smile:
        return False
    return True
if __name__ == "__main__":
    raw_smile_string = 'abc(b:)cdef(:()'
    print check_balance(raw_smile_string)


texts:
This is the domain class called WordType which has Id as its unique DB generated value and Name and Description as other values.

I was going through the Effective Java resource by Joshua Bloch and having a tough time assimilating the entire contents the first time. So I am looking at the implementation in my code by some other programmers so I learn by example and also validate the existing implementation. And the author states that for the usual classes the existing equals and hashcode works fine.

  The easiest way to avoid problems is not to override the equals
  method, in which case each instance is equal only to itself.

I am really skeptical if the below equals and hashcode implementation will work or if we should live with the default equals and hashcode without overriding them.

Each word would be unique as in dictionary for instance, and hence the ID would also be unique. If so, should I combine ID and Word to generate an equals and hashcode method?

public class WordType implements Serializable {
    private static final long serialVersionUID = 1L;

//... other properties, getters and setters

   @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {

        if (!(object instanceof WordType)) {
            return false;
        }
        WordType other = (WordType) object;

        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }
}


texts: Defining transpose on a collection of irregular collections

texts:
I was asked to submit my request for code review on https://stackoverflow.com/questions/10672046/defining-transpose-on-a-collection-of-irregular-collections here.

This is a follow-up to the post I made in https://stackoverflow.com/questions/1683312/is-there-a-safe-way-in-scala-to-transpose-a-list-of-unequal-length-lists/10663749#10663749. I want to propose a definition of transpose for a list of unequal-sized lists by viewing List[A] as a mapping from Int to A. First, here's why I think the transpose defined in the referenced post is problematic.

scala>  val l = List(List(1, 2, 3), List(4, 5), List(6, 7, 8))
l: List[List[Int]] = List(List(1, 2, 3), List(4, 5), List(6, 7, 8))

scala> val lt = transpose( l )
lt: List[List[Int]] = List(List(1, 4, 6), List(2, 5, 7), List(3, 8))

scala> val ltt = transpose( lt )
ltt: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 8), List(6, 7))

scala> l == ltt
res0: Boolean = false

So, transpose( transpose( l ) ) is not the same as l. The problem arises from the fact that this definition of transpose does not respect the precise indices associated with the elements (there is implicit "shifting" of elements when preparing the inner lists).

So I am proposing that transpose on a list of unequal-sized lists (List[List[A]]) be more abstractly viewed as an operation on a Map[Int,Map[Int,A]] (because a List[A] can be viewed as a Map[Int,A]). This operation is well-defined and can be further abstracted to operate on a Map[A,Map[B,C]] as follows:

def transpose[A,B,C]( mapOfMaps: Map[A,Map[B,C]] ) : Map[B,Map[A,C]] = {
  val innerKeys = ( mapOfMaps map { p => ( p._2.keys ) toList } ) flatten
  val outerKeys = ( mapOfMaps keys ) toList
  val allValues = innerKeys map { ik => outerKeys filter { ok => mapOfMaps( ok ).contains( ik ) } map { ok => ( ok, mapOfMaps( ok )( ik ) ) } toMap }
  ( innerKeys zip allValues ) toMap
}

To transform a list of lists to the more-abstract map of maps, zipping is convenient.

def listOfListsToMapOfMaps[A]( l : List[List[A]] ) : Map[Int,Map[Int,A]]= {
  val listOfMaps = l map { x => ( x.indices zip x ) toMap }
  ( listOfMaps.indices zip listOfMaps ) toMap
}

Now, things are clean:

scala> val m = listOfListsToMapOfMaps( l )
m: Map[Int,Map[Int,Int]] = Map(0 -> Map(0 -> 1, 1 -> 2, 2 -> 3), 1 -> Map(0 -> 4, 1 -> 5), 2 -> Map(0 -> 6, 1 -> 7, 2 -> 8))

scala>  val mt = transpose( m )
mt: Map[Int,Map[Int,Int]] = Map(0 -> Map(0 -> 1, 1 -> 4, 2 -> 6), 1 -> Map(0 -> 2, 1 -> 5, 2 -> 7), 2 -> Map(0 -> 3, 2 -> 8))

scala> val mtt = transpose( mt )
mtt: Map[Int,Map[Int,Int]] = Map(0 -> Map(0 -> 1, 1 -> 2, 2 -> 3), 1 -> Map(0 -> 4, 1 -> 5), 2 -> Map(0 -> 6, 1 -> 7, 2 -> 8))

scala> m == mtt
res1: Boolean = true

I see plenty of use for this generalized transpose operation in my work (and I'm sure for many others - across languages). But I'd like for people to review my transpose definition and implementation before I put it into my core library and start using it (I'm relatively new to Scala and am sure my implementation can be improved).


texts: JobTypeLogic and JobType classes in MVC business logic

texts:
I am working on an MVC solution.  My DAL layer I could solve with Repository classes, everything is working great.

But in my BLL layer I have repetitive code:

My CRUD is the same, my fields and consructor are different.
I can also have some extra methods.

Is there a way to solve this properly?

Class 1

public class JobTypeLogic
{
    #region Fields
    public JobType JobType { get; set; }
    private UnitOfWork unitOfWork = new UnitOfWork();
    public Repository<JobType> JobTypeEngine { get; set; }
    #endregion

    #region Constructor
    public JobTypeLogic()
    {
        JobType = new JobType();
        JobTypeEngine = unitOfWork.Repository<JobType>();
    }
    #endregion

    #region CRUD

    public void Add()
    {
        JobTypeEngine.Add(JobType);
    }

    public JobType Get(long id)
    {
        return JobType = JobTypeEngine.Get(id);
    }

    public void Edit()
    {
        JobTypeEngine.Edit(JobType);
    }

    public void Delete()
    {
        JobTypeEngine.Delete(JobType);
    }

    public List<JobType> List()
    {
        return JobTypeEngine.List.ToList();
    }

    #endregion

}

Class 2

public class JobLogic
{
    #region Fields
    public Job Job { get; set; }
    public IEnumerable<SelectListItem> JobTypeList { get; set; }
    private UnitOfWork unitOfWork = new UnitOfWork();
    public Repository<Job> JobEngine;
    private Repository<JobType> JobTypeEngine;
    #endregion

    #region Constructor
    public JobLogic()
    {
        Job = new Job();
        JobEngine = unitOfWork.Repository<Job>();
        JobTypeEngine = unitOfWork.Repository<JobType>();
        JobTypeList = GetJobTypeList();
    }
    #endregion

    #region CRUD

    public void Add()
    {
        JobEngine.Add(Job);
    }

    public Job Get(long id)
    {
        return Job = JobEngine.Get(id);
    }

    public void Edit()
    {
        JobEngine.Edit(Job);
    }

    public void Delete()
    {
        JobEngine.Delete(Job);
    }

    public List<Job> List()
    {
        return JobEngine.List.ToList();
    }

    #endregion

    #region Methode

    private IEnumerable<SelectListItem> GetJobTypeList()
    {
        JobTypeEngine = unitOfWork.Repository<JobType>();
        var jobs = JobTypeEngine.List
                    .Select(x =>
                            new SelectListItem
                            {
                                Value = x.ID.ToString(),
                                Text = x.Name
                            });

        return new SelectList(jobs, "Value", "Text");
    }

    #endregion

}


texts:
I have a dilemma. I have a messages table containing fields id, sender, receiver, body I need to select all users a given user has had a conversation with. A conversation may be a single message without a response.

Here's a show create table for you to see the indexes (as I may have set them up incorrectly):

CREATE TABLE `messages` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `sender` int(10) unsigned NOT NULL,
  `receiver` int(10) unsigned NOT NULL,
  `body` text,
  `datetime` datetime DEFAULT NULL,
  `seen` enum('0','1') NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `message_receiver` (`receiver`),
  KEY `msg_snd` (`sender`),
  CONSTRAINT `msg_rcv` FOREIGN KEY (`receiver`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  CONSTRAINT `msg_snd` FOREIGN KEY (`sender`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8

Here is basically the simplest way I could come up with to get the task done

SELECT DISTINCT
    (
        CASE SENDER
        WHEN 15 THEN
            receiver
        ELSE
            CASE receiver
        WHEN 15 THEN
            sender
        END
        END
    ) AS `user`
FROM
    messages
WHERE
    sender = 15
OR receiver = 15

However, I know that MySQL cannot take full advantage of indexes with OR comparisons (may be wrong), so I came up with an alternative of two queries which can both benefit from the indexes:

SELECT DISTINCT
    `user`
FROM
    (
        SELECT
            DISTINCT sender AS `user`
        FROM
            messages
        WHERE
            receiver = 15
        UNION
            SELECT
                DISTINCT receiver AS `user`
            FROM
                messages
            WHERE
                sender = 15
    ) AS conversations

Which one of these approaches is better in terms of performance and complexity?


texts:
I have written two methods that executes any type of HQL and returns data. Methods are like

public static Query getHqlQueryObject(String hql) throws Exception{

        Query query = null;
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction transaction = session.beginTransaction();
            query = session.createQuery(hql);
        } catch (Exception e) {
            System.out.println("Exception in Helper::getHqlQueryObject");
            e.printStackTrace();
        }
        return query;
    }

    public static List<Object> getHqlQueryData(Query query) throws Exception{
        List dataList = new ArrayList();
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction transaction = session.getTransaction();
            dataList = query.list();
            transaction.commit();
        } catch (Exception e) {
            System.out.println("Exception in Helper::getHqlQueryData");
            e.printStackTrace();
        }
        return dataList;
    }

I am calling this methods like this

Query query = Helper.getHqlQueryObject("from BookDetails where pkBookId = :pkBookId");
query.setParameter("pkBookId", new Long(1));
List dataList = Helper.getHqlQueryData(query);

My question is, is it right approach? or should I write session initialization code every time when I want to execute a query?


texts: Unit test for a CreateUser() method using JustMock lite

texts:
I'm new to unit testing and have created a unit test for a create user action method and it's passing the test. I'm not sure if this is the right way to unit test a create method.

This is my test method:

[TestMethod]
public void Create_User()
{
    Mapper.CreateMap<UserViewModel, User>();

    //Arrange
    var membershipRepository = Mock.Create<IStaticMembershipService>();
    var userMock = Mock.Create<MembershipUser>();
    Mock.Arrange(() => userMock.ProviderUserKey).Returns(1);
    Mock.Arrange(() => membershipRepository.GetUser()).Returns(userMock);
    var UserRepository = Mock.Create<IUserRepository>();

    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write("Creating Streams for Testing");
    writer.Flush();
    stream.Position = 0;
    var mockFile = Mock.Create<HttpPostedFileBase>();
    Mock.Arrange(() => mockFile.ContentType).Returns("application/pdf");
    Mock.Arrange(() => mockFile.FileName).Returns("Test.pdf");
    Mock.Arrange(() => mockFile.InputStream).Returns(stream);
    Mock.Arrange(() => mockFile.ContentLength).Returns(1);
    UserViewModel mockUserViewModel = new UserViewModel { Description = "TestDesc", Title = "Tester", UserId = 1, File = mockFile };

    Mock.Arrange(() => UserRepository.AddUser(Arg.IsAny<User>())).Returns(new OperationStatus{Status = true});
    //Act
    UserController controller = new UserController(UserRepository, membershipRepository);
    RedirectToRouteResult actionResult = (RedirectToRouteResult)controller.Create(mockUserViewModel);

    //Assert
    Assert.AreEqual(actionResult.RouteValues["Action"], "Index");
}

This is the action method:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(UserViewModel item)
{
    if (ModelState.IsValid)
    {
        var newUser = Mapper.Map<UserViewModel, User>(item);
        //Populates file name and content type to newUser
        UserHelper.PopulateFile(item.File, newUser);

        newUser.UserId = (int)_membershipService.GetUser().ProviderUserKey;

        var opStatus = _UserRepository.AddUser(newUser);
        if (!opStatus.Status)
            throw new System.Web.Http.HttpResponseException(new   HttpResponseMessage(HttpStatusCode.InternalServerError));

        return RedirectToAction("Index");
    }
    else
        return View(item);
}

Any relevant controller info:

private IUserRepository _UserRepository;
private IStaticMembershipService _membershipService;

public UserController(IUserRepository UserRepo, IStaticMembershipService membershipService)
{
    _UserRepository = UserRepo;
    _membershipService = membershipService;
}

IUserRepository:

public interface IUserRepository
{
    List<User> GetAllUsers(int Id);

    OperationStatus AddUser(User newUser);

    User GetUserById(int Id);
}

UserRepository containing definitions of above interfaces:

public List<User> GetAllUsers(int Id)
{
    using (DataContext)
    {
        return DataContext.Users.Where(j => j.Id == Id).ToList();
    }
}

public Journal GetUserById(int Id)
{
    using (DataContext)
        return DataContext.Users.SingleOrDefault(j => j.UserId == Id);
}

public OperationStatus AddUser(Journal newUser)
{
    var opStatus = new OperationStatus { Status = true };
    try
    {
        using (DataContext)
        {
            newUser.ModifiedDate = DateTime.Now;
            var j = DataContext.Users.Add(newUser);
            DataContext.SaveChanges();
        }
    }
    catch (Exception e)
    {
        //opStatus = OperationStatus.CreateFromException("Error adding user: ", e);
    }

    return opStatus;
}

The test is running fine. I'm just not sure if it's the right way for unit testing. Please let me know if I'm following the right approach here.


texts:
I am working on creating a Makefile for my ProjectEuler solutions. I need to compile each solution into a separate binary for personal timing purposes. Is it possible to pass the name of the rule to the -o option to remove some repeated code?

CXX = g++
CXXFLAGS = -std=c++0x
INC = -Iinclude/ -I../tools/

binaries=01sum35\
     02evenfibs\
     03largestprimefactor\
     04largestpallyproduct\
     05smallestmultiple\
     06sumsquaredifference\
     07tenthousandfirstprime\
     08largestproductinseries\
     09specialpythagtriplet

all: $(binaries)

01sum35:
    $(CXX) $(CXXFLAGS) 01sum35.cc $(INC) -o 01sum35

02evenfibs:
    $(CXX) $(CXXFLAGS) 02evenfibs.cc $(INC) -o 02evenfibs

03largestprimefactor:
    $(CXX) $(CXXFLAGS) 03largestprimefactor.cc $(INC) -o 03largestprimefactor

04largestpallyproduct:
    $(CXX) $(CXXFLAGS) 04largestpallyproduct.cc ../tools/tools.cc $(INC) -o 04largestpallyproduct

05smallestmultiple:
    $(CXX) $(CXXFLAGS) 05smallestmultiple.cc $(INC) -o 05smallestmultiple

06sumsquaredifference:
    $(CXX) $(CXXFLAGS) 06sumsquaredifference.cc $(INC) -o 06sumsquaredifference

07tenthousandfirstprime:
    $(CXX) $(CXXFLAGS) 07tenthousandfirstprime.cc ../tools/tools.cc $(INC) -o 07tenthousandfirstprime

08largestproductinseries:
    $(CXX) $(CXXFLAGS) 08largestproductinseries.cc ../tools/tools.cc $(INC) -o 08largestproductinseries

09specialpythagtriplet:
    $(CXX) $(CXXFLAGS) 09specialpythagtriplet.cc $(INC) -o 09specialpythagtriplet

clean:
    rm -f $(binaries)


texts: Using Euler-Maruyama method to solve Ornstein-Uhlenbeck equation (SDE)

texts:
I am trying to implement the Euler–Maruyama method and use it to solve the Ornstein–Uhlenbeck process. I am basing my code on the wikipedia page where a python implementation is shown. More generally I'm trying to get to grips with stochastic differential equations in c++.
This is my code
#include <iostream>
#include <fstream>
#include <random>
#include <vector>
#include <cmath>

using namespace std;

int num_sims = 5;
double t_init = 3;
double t_end  = 7;
int N         = 1000;
float dt      = (float)(t_end - t_init) / N;
double y_init = 0;

double c_theta = 0.7;
double c_mu    = 1.5;
double c_sigma = 0.06;

double dW ( double dt ){
    normal_distribution<double> distribution( dt , sqrt(dt) );
    random_device rd;
    default_random_engine generator(rd());

    return distribution(generator);
}

double mu( double y, double t ){
    return c_theta * (c_mu - y);
}

int main()
{
    vector<double> ts;
    for (double t = t_init; t < t_end + dt; t += dt){
        ts.push_back(t);
    }

    vector<double> ys(N+1, 0);
    ys[0] = y_init;

    for (int h = 0; h < num_sims; h+=1){
        for (int i = 1; i < ts.size(); i+=1 ){
            double t = (i - 1) * dt;
            double y = ys[i - 1];
            ys[i] = y + mu(y, t) * dt + c_sigma * dW(dt);

            cout << h << '\t' << ys[i] << endl;
        }
    }
    return 0;
}

This code seems to work well when I plot the results in python. My question is if this code can be written in a more efficient way? I feel like I should be using the boost packages on some level, and also maybe structures. I'm quite new to c++, so maybe my translation of the python code is a bit too word for word.


texts: Variadic template for concisely defining a tuple whose components are all the same type

texts:
C++11 provides a std::tuple template, but it requires the types of all the fields to be listed individually, which is inconvenient if there are many fields and they're all the same type.  If I want a tuple of, say, 10 integers, instead of writing std::tuple<int, int, int, int, int, int, int, int, int, int>, I'd like to be able to just write something like tuple_of<10, int>.

To that end, I've written a template that expands a number into that many copies of a type:

template <unsigned int n, typename T>
struct tuple_of {
private:

  // Adds another copy of T to the list
  template <unsigned int m, typename... Ts>
  struct tuple_builder {
    using type = typename tuple_builder<m-1, T, Ts...>::type;
  };

  // Makes a tuple out of all the copies of T that have been listed
  template <typename... Ts>
  struct tuple_builder<0, Ts...> {
    using type = std::tuple<Ts...>;
  };

public:

  tuple_of() = delete;  // Prevent accidental instantiation

  using type = typename tuple_builder<n, T>::type;
};

// Convenience alias
template <unsigned int n, typename T>
using tuple_of_t = typename tuple_of<n, T>::type;

Now you can write either tuple_of<10, int>::type or tuple_of_t<10, int>.

This works, but it seems a little awkward.  A few things in particular bother me:

I don't really like having to write either ::type or the _t suffix of the convenience alias; I'd rather just write tuple_of<10, int>.  I've followed the pattern established by the templates in the standard <type_traits> header — e.g. std::result_of_t<T> is an alias for std::result_of<T>::type — but tuple_of isn't a type trait so I don't know if I should be following that convention.
I've made the template a struct because that seems to be the norm for templates used in metaprogramming, but it contains a private helper template that I don't really want to expose, and it's a little weird to have private stuff in a struct.
This is the first variadic template I've written, so I'm not sure that my tuple_builder is the most elegant way to build a list of n copies of a type.
While testing, I accidentally created an instance of the template type itself, rather than the tuple type it produces, by writing tuple_of<10, int> instead of tuple_of<10, int>::type.  To avoid that mistake in the future, I deleted the constructor.  I don't know whether that's something templates like this "should" do; the templates in <type_traits> don't have deleted constructors.

Can this template be improved?


texts: Group a list of `dict` by all keys except one

texts:
I have a function that I use to convert a list of dictionaries into a list of tuples, similar to itertools.groupby() would do in an ideal world.  The goal is to make a list of {unique-dict} => [list of values].  I'm having a hard time explaining it, so I hope the example makes it clear.

I couldn't find a thing on google, so I wrote it pretty quickly, and I am wondering if there is a better way to do this (or a standard library even)

Naming things is hard... what is a better one?
This is a task I performed fairly often when receiving user input
The keys in each dict may not be consistent (some may be missing)
It is OK to destroy or mangle the original input list & items
Validation is done before calling, so 'key_field' is always present
It is expected that values can be duplicated in the list.

{ status: 1 } => [1,2,3,4,1,2] is ok, if the values are actually present twice.

Simple little python function:

def group_by_excluding_key(list_of_dicts, key_field):
    """
    Takes a list of `dict` items and groups by ALL KEYS in the dict EXCEPT the key_field.
    :param list_of_dicts: List of dicts to group
    :param key_field: key field in dict which should be excluded from the grouping
    """

    output = []

    for item in list_of_dicts:
        found = False
        item_key = item.pop(key_field)

        for existing_group, found_keys in output:
            if existing_group.viewitems() == item.viewitems():
                found_keys.append(item_key)
                found = True
                break

        if not found:
            output.append((item, [item_key]))

    return output

Example Input/Output

from pprint import pprint

data = [
    {'id': 1, 'status': 1, 'product': 1},
    {'id': 2, 'status': 1, 'product': 1},
    {'id': 7, 'status': 1, 'product': 2},
    {'id': 9, 'status': 1, 'product': 2},
    {'id': 3, 'status': 1, 'product': 1},
    {'id': 4, 'status': 1, 'product': 1},
    {'id': 8, 'status': 1, 'product': 2},
    {'id': 1, 'status': 1, 'product': 1},
]

results = group_by_excluding_key(data, 'id')

pprint(results)

# [({u'product': 1, u'status': 1}, [1, 2, 3, 4, 1]),
#  ({u'product': 2, u'status': 1}, [7, 9, 8])]


texts: Using Fibonacci sequence to generate musical melodies

texts:
I recently started picking up the Haskell programming language. I've managed to learn other languages rather quickly, but I'm still having a difficult time grasping some of the basics of Haskell.

I decided to practice and wrote a program that calculates the Fibonacci Sequence (original, I know) a certain amount of times and adds the results to a list, then divides each number in the list by 7 and creates a new list of the remainders of that division. It then assigns a musical note letter based in A minor (A, B, C, D, E, F, and G), and prints out each letter. The idea was to give me new ideas for writing melodies.

The program works, but with how efficient Haskell is I feel like it's way too long for what it does. How would you guys suggest re-writing this and what are some shortcuts I can use to write better code?

Here's the program:

import Data.List
import System.IO

fibo a b = a:fibo b (a+b)
divBy7 x = x `mod` 7
calcNums = take 16 $ map divBy7(fibo 0 1)
returnNote :: Int -> String
returnNote n
  | (n == 0) = "A"
  | (n == 1) = "B"
  | (n == 2) = "C"
  | (n == 3) = "D"
  | (n == 4) = "E"
  | (n == 5) = "F"
  | (n == 6) = "G"
-- the number will never be higher than 6 due to the pisano period

output = map returnNote(calcNums)

I'm just running ghci and asking it to return output


texts:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef struct Node NODE;

struct Node {
  int value;
  int is_leaf;
  struct Node *right;
  struct Node *left;
};

NODE *new_leaf(void) {
  NODE *leaf = malloc(sizeof(NODE));
  assert(leaf);
  leaf->is_leaf = 1;
  leaf->value = 0;
  leaf->right = NULL;
  leaf->left = NULL;
  return leaf;
}

int insert(NODE *node, int value) {
  assert(node);
  if (node->is_leaf) {
    node->is_leaf = 0;
    node->value = value;
    node->left = new_leaf();
    node->right = new_leaf();
  } else if (node->value < value) {
    return insert(node->left, value);
  } else if (node->value > value) {
    return insert(node->right, value);
  }
  return -1;
}

int contains(NODE *node, int value) {
  assert(node);
  if (node->is_leaf) {
    return 0;
  } else if (node->value < value) {
    return contains(node->left, value);
  } else if (node->value > value) {
    return contains(node->right, value);
  }
  return 1;
}

int max_height(NODE *node) {
  assert(node);
  if (node->is_leaf) {
    return 0;
  }
  int left_height = max_height(node->left);
  int right_height = max_height(node->right);
  if (left_height > right_height) {
    return 1 + left_height;
  } else {
    return 1 + right_height;
  }
}

void destroy(NODE *tree) {
  free(tree);
}

int main(void) {
  NODE *tree = new_leaf();
  insert(tree, 7);
  printf("contains 7? : %d\n", contains(tree, 7));
  insert(tree, 6);
  printf("contains 6? : %d\n", contains(tree, 6));
  insert(tree, 5);
  printf("contains 5? : %d\n", contains(tree, 5));
  printf("height should be 3, is : %d\n", max_height(tree));
  insert(tree, 8);
  printf("contains 8? : %d\n", contains(tree, 8));
  printf("height should be 3, is : %d\n", max_height(tree));
  printf("no contains 1? : %d\n", contains(tree, 9));
  destroy(tree);
}

Looking for general style advice, and if I missed any memory leaks.

Specific question: does destroying the tree at the end free up all of the memory allocated for every node in the tree? If so, how? If not, how can I ensure that occurs? Also, am I using asserts correctly? It's very different than the languages I have used previously.


texts:
BudgetCode is in the format 'xxxx-yyyyy-zzzzz'. This splits it correctly but I think that there has to be a more efficient way.

Select
       substring(pc.BudgetCode,1, CHARINDEX('-',pc.BudgetCode)-1) as Cost_Center,
       substring(Substring(pc.BudgetCode,Charindex('-',pc.BudgetCode)+1,len(pc.BudgetCode)),1, CHARINDEX('-',Substring(pc.BudgetCode,Charindex('-',pc.BudgetCode)+1,len(pc.BudgetCode)))-1) as Account_Code,
       Substring(Substring(pc.BudgetCode,Charindex('-',pc.BudgetCode)+1,len(pc.BudgetCode)),Charindex('-',Substring(pc.BudgetCode,Charindex('-',pc.BudgetCode)+1,len(pc.BudgetCode)))+1,len(Substring(pc.BudgetCode,Charindex('-',pc.BudgetCode)+1,len(pc.BudgetCode)))) as Slid_Code
from pc


texts: How to find position (array index ) of a number in a given array?

texts:
I have to find the position (array index) of a number in an array, the number can lie in between any other two numbers in the array. I have written code for this but I want some alternative way to do this.

example: let the array be given as

float arr[]={1.5, 3.65, 4.9, 8.4, 10.6, 17.5, 19.45, 21.86, 25.67, 30.65};

Now I have to find the position of 12.6 in the given array, since 12.6 lies between 10.6 and 17.5 in the above array so, it should return array index as 4.

Is there any other way to do this? I know it can be done by using binary search but I don't know how to implement it (since the number is not present in array)

The array is sorted (ascending order)

#include<stdio.h>
int main()
{
int position;
int i;
float num=12.6; // position of this number has to be determined i.e. it lies between 10.6
// and 17.5 in the array given below so it should give array index as 4
float arr[]={1.5, 3.65, 4.9, 8.4, 10.6, 17.5, 19.45, 21.86, 25.67, 30.65}; // any random array

for(i=0;i<10;i++)
{
if(arr[i] > num)
{
position=i-1;
break;
}
}
printf("array index is %d",position); // this gives index as 4

return 0;
}


texts: Algorithm with byte shifts and BCD calculation

texts:
I'm trying to develop an algorithm that generates a 16-digit validation number to interact with a given system.

This is how the algorithm should be implemented:

I have implemented it, and have it working with 2 of 3 test cases that I have found (I will post them below).

The implementations goes as:

public static String Generate(byte[] _MachineId, byte[] _SN)
{
        try
        {
            byte[] step1 = new byte[6]
            {
                _SN[2],
                _SN[1],
                _SN[0],
                _MachineId[2],
                _MachineId[1],
                _MachineId[0]
            };

            byte[] step2 = new byte[6]
            {
                step1[0],
                step1[1],
                (byte)(step1[2] ^ step1[0]),
                (byte)(step1[3] ^ step1[1]),
                (byte)(step1[4] ^ step1[0]),
                (byte)(step1[5] ^ step1[1])
            };

            var crc45 = new byte[2] { step2[4], step2[5] }.GetCRCAsByteArray(0);
            var crc23 = new byte[2] { step2[2], step2[3] }.GetCRCAsByteArray(0);
            var crc01 = new byte[2] { step2[0], step2[1] }.GetCRCAsByteArray(0);

            byte[] step3 = new byte[6]
            {
                crc01[0],
                crc01[1],
                crc23[0],
                crc23[1],
                crc45[0],
                crc45[1]
            };

            string bin_to_BCD_543 = ((uint)((((0x00 << 4) | step3[5]) << 16) | ((step3[4] << 8) | step3[3]))).ToString().PadLeft(8, '0');
            string bin_to_BCD_210 = ((uint)((((0x00 << 4) | step3[2]) << 16) | ((step3[1] << 8) | step3[0]))).ToString().PadLeft(8, '0');

            String step4pre = bin_to_BCD_543 + bin_to_BCD_210;
            Func<String, int[]> convertToIntArray =
                    new Func<string, int[]>(
                    (str) =>
                    {
                        List<int> result = new List<int>();
                        foreach (var c in str.ToCharArray()) result.Add(int.Parse(c.ToString()));
                        return result.ToArray();
                    }
                );
            int[] step4 = convertToIntArray(step4pre);

            int[] step5 = step4.ToList().ToArray();

            step5[8] = step4[8] | ((step4.ToList().GetRange(8, 8).Sum() % 5) << 1);
            step5[0] = step4[0] | ((step4.ToList().GetRange(0, 8).Sum() % 5) << 1);

            String validation = String.Join("", step5);
            return validation;
        }
        catch (Exception exc)
        {
            System.Diagnostics.Trace.TraceError("Error generating Validation number. Error => " + exc.ToString());
        }
        return "";
    }

This, are the 2 test cases that I have working:

ID = {0x21, 0x43, 0x65}, SN = {0x01, 0x00, 0x00} -> VN = "6429188185446104"
ID = {0x21, 0x43, 0x65}, SN = {0x02, 0x00, 0x00} -> VN = "2701773123879856"

I have found a 3rd case in another document, that should satisfy this:

ID = {0x01, 0x00, 0x10}, SN = {0x99, 0x00, 0x00} -> VN = "0230633823748784"

But this one does not works for me, so my questions are:

Is the algorithm implementation OK in terms of satisfying the requirements?
How can this implementation be improved?


texts: Computing inverse of modified matrix using Sherman-Morrison formula

texts:
I have the following implementation that takes in symmetric matrix W and returns matrix C
import torch
import numpy as np
import time

W = torch.tensor([[0, 1, 0, 0, 0, 0, 0, 0, 0],
              [1, 0, 1, 0, 0, 1, 0, 0, 0],
              [0, 1, 0, 3, 0, 0, 0, 0, 0],
              [0, 0, 3, 0, 1, 0, 0, 0, 0],
              [0, 0, 0, 1, 0, 1, 1, 0, 0],
              [0, 1, 0, 0, 1, 0, 0, 0, 0],
              [0, 0, 0, 0, 1, 0, 0, 1, 0],
              [0, 0, 0, 0, 0, 0, 1, 0, 1],
              [0, 0, 0, 0, 0, 0, 0, 1, 0]])

A = W.clone()
[n_node, _] = A.shape
nI = n_node * torch.eye(n_node)

# -- method 1
C = torch.empty(n_node, n_node)

for i in range(n_node):
    for j in range(i, n_node):
        B = A.clone()
        B[i, j] = B[j, i] = 0
        C[i, j] = C[j, i] = torch.inverse(nI - B)[i, j]

As you can see, I have a matrix nI - B and change one element at each loop and compute its inverse. Im trying to use Sherman-Morrison formula to enhance the performance of the code. Here is my implementation:
# -- method 2
c = torch.empty(n_node, n_node)

inv_nI_A = torch.inverse(nI - A)
b = torch.div(A, 1 + torch.einsum('ij,ij->ij', A, inv_nI_A))
inv_nI_A_ = inv_nI_A.unsqueeze(1)

for i in range(n_node):
    for j in range(i, n_node):
        c[i, j] = c[j, i] = (inv_nI_A - b[i, j] * torch.matmul(inv_nI_A_[:, :, i], inv_nI_A_[j, :, :]))[i, j]

I was wondering if I can do further enhancements on my implementation. Thanks!
PS: W is not necessarily a sparse matrix.


texts: Merging two lists of dicts based on the value of a specific key

texts:
I'm combining two lists of dicts, based on the value of the key 'time'.

If have two lists, for example:

a=[{'time': '25 APR', 'total': 10, 'high': 10},
   {'time': '26 APR', 'total': 5, 'high': 5}]

b=[{'time': '24 APR', 'total': 10, 'high': 10},
   {'time': '26 APR', 'total': 15, 'high': 5}]

These lists contain values per day, for a specific source, say a and b.

I would like to add the dicts in the lists, based on the value of the key 'time'. So the end result would be:

c=[{'time': '24 APR', 'total': 10, 'high': 10},
   {'time': '25 APR', 'total': 10, 'high': 10},
   {'time': '26 APR', 'total': 20, 'high': 10}]

Notice that the results for 26 APR are added.

The way I do this now, is as follows:

from collections import Counter
import itertools

lst = sorted(itertools.chain(totals_30_days, past_30_days), key=lambda x: x['time'])

f = []

for k,v in itertools.groupby(lst, key=lambda x:x['time']):
    v = list(v)

    # Check if there are more than one item, because adding an empty Counter()
    # will delete any keys with zero or negative values.
    if len(v) > 1:
        e = Counter()
        for i in v:
            c = Counter(i)
            time = c.pop('time', None)
            e = e + c
        e['time'] = time
        f.append(dict(e))
    else:
        f.append(v[0])
print(f)

The result is correct:

[{'high': 10, 'total': 10, 'time': '24 APR'}, {'high': 10, 'total': 10, 'time': '25 APR'}, {'high': 10, 'total': 20, 'time': '26 APR26 APR'}]

But I wonder if it could be more efficient. Any ideas?


texts: Different character outputs using loops and strings

texts:
I've just given this as a response to an absolute beginner on SO, and I'm wondering how terrible it is.

Output for an odd number of lines:

>
>>>
>>>>>
>>>
>

Output for an even number of lines:

>
>>>
>>>>>
>>>>>
>>>
>

The code:

int lines = 7;
int half = lines/2;
String carat = ">";
int i;

//better to declare first or does it not matter?

if(lines%2==0){boolean even = true;}
else{boolean even = false;}

for(i=1;i<=lines;i++){
        System.out.println(carat + "\n");
        if(i==half && even){System.out.println(carat+"\n");}
        if(((i>=half && even) || (i>=half+1)) && i!=lines){
                carat = carat.substring(0,carat.length()-2);
        }else{
                carat = carat + ">>";
        }
}

This code just seems so ugly, not considering the fact that there is no method that takes number of lines and that it is abusing integer rounding.


texts:
This script makes it possible for badges to onebox in Chat.

The install requires Tamper/GreaseMonkey. Click here to install,
and it's on GitHub and StackApps!

// ==UserScript==
// @name Badge Oneboxer
// @description Converts tag-like badge comments to badges
// @version 0.24
// @match *://chat.stackexchange.com/rooms/*
// @match *://chat.stackoverflow.com/rooms/*
// @match *://chat.meta.stackexchange.com/rooms/*
// @author The-Quill
// @downloadURL  https://raw.githubusercontent.com/The-Quill/badge-oneboxer/master/badge-oneboxer.user.js
// @updateURL https://raw.githubusercontent.com/The-Quill/badge-oneboxer/master/badge-oneboxer.user.js
// @grant GM_getResourceText
// @resource    badges  https://rawgit.com/The-Quill/badge-oneboxer/master/badges.json
// @run-at document-end
// ==/UserScript==

    'use strict';
    var Badges;
    $.get("https://rawgit.com/The-Quill/badge-oneboxer/master/badges.json", function(data){
        Badges = data;
    }).done(function(){
        var m = new MutationObserver(function(){
            ReplaceAll();
        });
        m.observe(document.getElementById("chat"), {childList: true});
        ReplaceAll();
    });
    function ReplaceAll(){
        var messages = document.getElementsByClassName('message');
        for (var i = 0, length = messages.length; i < length - 1; i++){
            ReplaceText(messages[i])
        }
    }
    var regex = /(\[badge:([a-zA-Z#.\-]+)\])/i;
    var ColourTransforms = {
        bronze: "CC9966",
        silver: "C5C5C5",
        gold: "FFCC00"
    };
    function ReplaceText(node){
        if (!node) return false;
        var badgeProperties = SelectBadgeProperties(node.innerText);
        if (!badgeProperties) { return false };
        if (badgeProperties.total == "") return false;
        node.innerHTML = node.innerHTML.replace(
            badgeProperties.total,
            "" +
            "<svg version=\"1.1\" height=\"18\" width=\"15\" xmlns=\"http://www.w3.org/2000/svg\"><circle fill=\"#" +
            (Badges.hasOwnProperty(badgeProperties.name) ? ColourTransforms[Badges[badgeProperties.name]] : "000") +
            "\" r=\"3\" cy=\"13.5\" cx=\"3\" /></svg>" +
            badgeProperties.name + ""
        );
        if (HasBadgeText(node.innerText)){
            console.log("again");
            ReplaceText(node);
        }
    };
    function HasBadgeText(text){
        return regex.test(text);
    }
    function SelectBadgeProperties(text){
        if (!HasBadgeText(text)) return false;
        var matchesArray = text.match(regex);
        return {
            total: matchesArray[0],
            name:  matchesArray[2]
        };
    }


texts: Find and display the position of a word in a sentence

texts:
How can I simplify this code:

Public Class Form1
Private Sub BtnPositions_Click(sender As Object, e As EventArgs) Handles BtnPositions.Click
    ' 'txtSentence.Text = "The cat sat on the mat" ' Temp for testing

    If TxtAddSentence.Text = "" Then
        MsgBox("The text you are searching is empty, so there are no matches." & vbCrLf & "Please enter some text and retry.")
    End If

    Dim WordArray() = {""}
    Dim strSearchWord As String

    BuildWordArray(TxtAddSentence.Text, WordArray)
    strSearchWord = TxtAddWord.Text
    FindPositionOfWords(strSearchWord, WordArray)

    If TxtAddSentence.Text = "" Then
        MsgBox("The sentence box is empty, so there are no matches.")
    End If

End Sub
Private Sub BuildWordArray(ByVal strText, ByRef strArray)
    Dim strTextArray1() = Split(strText, " ")
    strArray = strTextArray1
End Sub

Private Sub FindPositionOfWords(ByVal strSearchWord, ByVal strWordList)

    Dim intIndex As Integer = 1
    Dim strPosn As String = ""
    For Each strWord As String In strWordList
        If UCase(strWord) = UCase(strSearchWord) Then
            If strPosn = "" Then
                strPosn = strPosn & Str(intIndex)
            Else
                strPosn = strPosn & "," & Str(intIndex)
            End If
        End If
        intIndex = intIndex + 1
    Next
    If strPosn = "" Then
        MsgBox("The Search Word Here Box Is Empty", MsgBoxStyle.Exclamation)
    Else
        MsgBox("The word '" & strSearchWord & "' was found at positions" & strPosn)
    End If
End Sub
End Class


texts:
I have a FaultType enum with more than 100 members:

public enum FaultType
{
    FaultType1,
    FaultType2,
    FaultType3,
    FaultType4,
    FaultType5,
}

And I have a FaultTypeConstants class corresponding to FaultType:

public class FaultTypeConstants
{
    public const int FaultType1 = 600;
    public const int FaultType2 = 100;
    public const int FaultType3 = 453;
    public const int FaultType4 = 200;
    public const int FaultType5 = 300;
}

Now, I want to populate the List<FaultType> based on FaultTypeConstants values:

public static List<FaultType> GetFaults(List<int> FaultConstants)
{
    var faults = new List<FaultType>();
    FaultConstants.ForEach(fc => {
        switch (fc)
        {
            case FaultTypeConstants.FaultType1:
                faults.Add(FaultType.FaultType1);
                break;
            case FaultTypeConstants.FaultType2:
                faults.Add(FaultType.FaultType2);
                break;
            case FaultTypeConstants.FaultType3:
                faults.Add(FaultType.FaultType3);
                break;
            case FaultTypeConstants.FaultType4:
                faults.Add(FaultType.FaultType4);
                break;
            case FaultTypeConstants.FaultType5:
                faults.Add(FaultType.FaultType5);
                break;
            default:
                break;
        }
    });

    return faults;
}

Is there a better way to do this?


texts:
I have a meta-search engine system, i implemented mainly using static classes. The query pre processing module consists of the following static methods

function queryPreprocessing() { }
queryPreProcessing.removeStopWords = function (query){ // code here}
queryPreProcessing.stemmer = function (w) { //code here }
queryPreProcessing.convertBoolean = function (w){ //code here}

Technically the query pre processing modules takes as input a string (the query) and performs the above named functions on it. For example:

var query = $("#textbox").val();
query = queryPreProcessing.removeStopWords(query) ;
query = queryPreProcessing.stemmer(query) ;
query = queryPreProcessing.convertBoolean(query) ;

For simplicity, it was easier for me to make all the methods static and call them when needed but my question is: Is this the best way of doing it?


texts: TapeEquilibrium Codility implementation not achieving 100%

texts:
Given the following task description from here :

  A non-empty zero-indexed array A consisting of N integers is given.
  Array A represents numbers on a tape.

  Any integer P, such that 0 < P < N, splits this tape into two
  non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].

  The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|

  In other words, it is the absolute difference between the sum of the
  first part and the sum of the second part.

  For example, consider array A such that:

  A[0] = 3
  A[1] = 1
  A[2] = 2
  A[3] = 4
  A[4] = 3

  We can split this tape in four places:

P = 1, difference = |3 − 10| = 7
P = 2, difference = |4 − 9| = 5
P = 3, difference = |6 − 7| = 1
P = 4, difference = |10 − 3| = 7

  Write a function:

def solution(A)

  that, given a non-empty zero-indexed array A of N integers, returns
  the minimal difference that can be achieved.

  For example, given:

  A[0] = 3
  A[1] = 1
  A[2] = 2
  A[3] = 4
  A[4] = 3

  the function should return 1, as explained above.

  Assume that:

  N is an integer within the range [2..100,000]; each element of array A
  is an integer within the range [−1,000..1,000]. Complexity:

  expected worst-case time complexity is O(N);
  expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).

  Elements of input arrays can be modified.

I decided to implement an algorithm that with 2 counters/pointers (one from leftmost and another one from rightmost of the array input) representing the total sum of values that the pointer(s) have traversed.
The process works by first deciding which pointer to move closer to the other in each iteration, which is looking the next element directly next to the location of the current pointer, attempt to temporarily sum the value to the pointer, and then find the absolute difference between the other pointer.
The absolute difference is also calculated for the other pointer, and then compared against each other's pointer temporarily accumulated value, to find out which one yields lower absolute difference.
The pointer move that yields the lowest absolute difference then performs the actual summation to the pointer, and that particular pointer moves for that iteration.

The following is my code :

from math import fabs

def solution(A):
    l_ptr = 0
    r_ptr = A.__len__() - 1
    l_sum = A[l_ptr]
    r_sum = A[r_ptr]
    while l_ptr < r_ptr - 1:
        if fabs(l_sum + A[l_ptr + 1] - r_sum) > fabs(l_sum - (r_sum + A[r_ptr - 1])):
            r_ptr -= 1
            r_sum += A[r_ptr]
        else:
            l_ptr += 1
            l_sum += A[l_ptr]
    return (int)(fabs(l_sum - r_sum))

In the test case, I didn't manage to achieve 100% test accuracy, and I'm not sure exactly why, but I think perhaps it has something to do with the pointer not being able to look for the array element that are several steps away at a given iteration and the possibility of having negative value.
The followings are the test cases that it fails on according to Codility :

▶ small_random
random small, length = 100 ✘WRONG ANSWER
got 269 expected 39
▶ large_ones
large sequence, numbers from -1 to 1, length = ~100,000 ✘WRONG ANSWER
got 228 expected 0
▶ large_random
random large, length = ~100,000 ✘WRONG ANSWER
got 202635 expected 1

Obviously provided that it's evaluation of a test set, the actual input data for the test are not given, so it's more difficult for me to figure out what part of my algorithm that is incorrect and the causes.
Could someone provide an explanation (preferably with a sample input data) what I misunderstood and the cause?
Thank you in advance.


texts: Are my forms a danger towards code injection?

texts:
I'm writing a PHP tutorial and I would like to display some forms where the users could enter values that are displayed in the same webpage, just as a demonstration.

The forms do nothing special, they only use print instructions to display the input.

I would like to know if these apparently innofensive forms could be a real danger for my server because of script injection.

The code that processes the form is:

<?php
      if (array_key_exists('user', $_POST)) {
            print "Hello, " . $_POST['user'];
      } else {
            print "Waiting for your input...";
      }
?>


texts: Linked List Interview Code methods, runtime, and edge cases

texts:
Refactored code here

I want to write a very simple Linked List with only 3 methods Append, Remove and Print. This is not for production and is to be treated as code that could be used in an interview or a quick and dirty prototype. I'm really curious about the approach I've taken here to ensure no duplicates appear in my Linked List. I feel the data structure will be much easier to work with if remove any complexity around duplicate data and want to use this Linked List to implement a Stack, or Queue, or Binary Search Tree etc. I had int data before as the member data field for my Linked List and don't want to make this overly complex by introducing a concept of ids.

First I'd like to know if my member functions for the Linked List have any edge cases I am not catching and any improvements I can make to run time efficiency . Anyway I can simplify this code further with c++11 features, shorter variable names or any other suggestions would be appreciated too.

#include <iostream>

using namespace std;

struct Node
{
    int id;
    Node* next;

    Node(int id) : id(id), next(nullptr) { }

    void append(int newId) {
        Node* current = this;
        while (current->next != nullptr) {
            if (current->id == newId) {
                return;
            }
            else {
                current = current->next;
            }
        }
        current->next = new Node(newId);
    }

    void remove(int targetId) {
        Node* current = this;
        Node* previous;
        while (current->id != targetId) {
            if (current->next != nullptr) {
                previous = current;
                current = current->next;
            }
            else {
                cout << "node not found :(\n";
                return;
            }
        }
        if (current->next == nullptr) {
            delete current;
            previous->next = nullptr;
        }
        else {
            Node* danglingPtr = current->next;
            current->id = current->next->id;
            current->next = current->next->next;
            delete danglingPtr;
        }
    }

     void print() {
        if (this->next == nullptr) {
            cout << this->id << endl;
        }
        else {
            cout << this->id << " ";
            this->next->print();
        }
    }
};

int main()
{
    Node list(1);

    list.append(2);
    list.append(3);
    list.append(4);
    list.print();

    list.remove(3);
    list.print();

    list.remove(4);
    list.print();

    list.remove(1337);
}


texts: Testing class which returns big dictionary

texts:
I have simple class with the public build method I want to test. Currently I assert all values it returns in every test. Is it a good practice or I should write one test for static values and in other tests only check values which change depending on input?

Implementation

class FiltersAttachment:
    TYPE_OPTIONS = [
        {"text": "All types", "value": "all"},
        {"text": ":link: Webpages", "value": "web_pages"}
    ]

    STATUS_OPTIONS = [
        {"text": "Available / Unavailable", "value": "all"},
        {"text": ":white_circle: Available", "value": "available"},
        {"text": ":red_circle: Unavailable", "value": "unavailable"}
    ]

    @classmethod
    def _filter_options(cls, options, selected):
        return list(filter(lambda t: t['value'] == selected, options))

    @classmethod
    def build(cls, check_type='', status=''):
        return {
            'fallback': 'Filters',
            'callback_id': 'resource_filters',
            'color': '#d2dde1',
            'mrkdwn_in': ['text'],
            'actions': [
                {
                    'name': 'resource_type',
                    'text': 'Type',
                    'type': 'select',
                    'options': cls.TYPE_OPTIONS,
                    'selected_options': cls._filter_options(
                        cls.TYPE_OPTIONS, check_type)
                },
                {

                    'name': 'resource_status',
                    'text': 'Status',
                    'type': 'select',
                    'options': cls.STATUS_OPTIONS,
                    'selected_options': cls._filter_options(
                        cls.STATUS_OPTIONS, status)
                }
            ]
        }

Tests

class TestFiltersAttachment(TestCase):
    def assert_attachment(self, attachment):
        self.assertEqual(attachment['fallback'], 'Filters')
        self.assertEqual(attachment['callback_id'], 'resource_filters')
        self.assertEqual(attachment['color'], '#d2dde1')
        self.assertEqual(attachment['mrkdwn_in'], ['text'])

        type_action = attachment['actions'][0]
        self.assertEqual(type_action['name'], 'resource_type')
        self.assertEqual(type_action['text'], 'Type')
        self.assertEqual(type_action['type'], 'select')
        self.assertEqual(type_action['options'][0]['text'], 'All types')
        self.assertEqual(type_action['options'][0]['value'], 'all')
        self.assertEqual(type_action['options'][1]['text'], ':link: Webpages')
        self.assertEqual(type_action['options'][1]['value'], 'web_pages')

        status_action = attachment['actions'][1]
        self.assertEqual(status_action['name'], 'resource_status')
        self.assertEqual(status_action['text'], 'Status')
        self.assertEqual(status_action['type'], 'select')
        self.assertEqual(status_action['options'][0]['text'], 'Available / Unavailable')
        self.assertEqual(status_action['options'][0]['value'], 'all')
        self.assertEqual(status_action['options'][1]['text'], ':white_circle: Available')
        self.assertEqual(status_action['options'][1]['value'], 'available')
        self.assertEqual(status_action['options'][2]['text'], ':red_circle: Unavailable')
        self.assertEqual(status_action['options'][2]['value'], 'unavailable')

    def test_all_type_selected(self):
        attachment = FiltersAttachment.build(check_type='all')
        self.assert_attachment(attachment)

        selected_type = attachment['actions'][0]['selected_options'][0]
        self.assertEqual(selected_type['text'], 'All types')
        self.assertEqual(selected_type['value'], 'all')

    def test_all_status_selected(self):
        attachment = FiltersAttachment.build(status='all')
        self.assert_attachment(attachment)

        selected_status = attachment['actions'][1]['selected_options'][0]
        self.assertEqual(selected_status['text'], 'Available / Unavailable')
        self.assertEqual(selected_status['value'], 'all')


texts: Array Duplicate Item Filtering by Element Value

texts:
I'm learning to code PHP and gave myself a challenge: Filter array data by matching a specific element value for duplication. I went through it logically on paper then wrote code and it worked on the first try :) But I bet it is the most inefficient way, so to learn I would like to compare it against what others would do. Below is my code. The array is just a few elements with keys like name and id. My result is a list of only items with unique ids from an array with many duplicate ids but different names.

Also, part of the challenge was testing XML, JSON, and Arrays so I made the original data XML and used SimpleXML but made a copy of that data as a PHP array and worked with that to do filtering (XPath challenge next).

Thanks for looking and any suggested improvements that I can learn from.

//$items is a SimpleXML array of items with name and id elements with many duplicate ids but different names.

//first iteration of id collection
$ids = array();
$countedIds = array();
//convert simplexml array $items to normal array (copy)
$itemsArray = json_decode(json_encode($items), TRUE);
foreach ($itemsArray as $idItem)
{
    //collection all ids
    $ids[] = $idItem['id'];
}
//count number of each id and store in separate array
$countedIds = array_count_values($ids);
#print_r($countedIds);

//start cleaning out duplicates
foreach($itemsArray as $key => &$item)
{
    //clear any whitespace (thanks internets)
    #$thisid = trim($item->id); //if using simplexml
    $thisid = trim($item['id']);
    //check if this id is duplicated (multiple copies) in array
    if($countedIds[$thisid] >1)
    {
        echo $thisid . "item has duplicates (" . $countedIds[$thisid] . ")
";
        //add found dupes to separate array
        $dupes[] = $thisid;
        //remove this item from $itemsArray and original $items simplexml array
        unset($itemsArray[$key]);
        unset($items[$key]);
        echo "removed element index " . $key . $item . "

";
        //remove this id from $ids array
        unset($ids[$key]);
        //clear out the counted ids
        unset($countedIds);
        //make a fresh array for counting ids
        $countedIds = array();
        //get updated id count
        $countedIds = array_count_values($ids);

        //test simplexml unset?
        #unset($sxe->$this->channel->item);
    }
}
//review results
print_r($countedIds);
print_r($ids);
print_r($dupes);
print_r($itemsArray);
print_r($items);


texts:
I want to create a circular queue using a linked list. I also want to create many instances of that data structure (queue) without repeating the code.

This is what I came up with:

#include <stdio.h>
#include <stdlib.h>
struct queue
{
    int info;
    struct queue *next;
    struct queue *front;
    struct queue *rear;
};
void create(struct queue **q)
{
    (*q)->next = 0;
    (*q)->front = 0;
    (*q)->rear = 0;
}
struct queue* makenode(int item){
    struct queue* p = (struct queue*)malloc(sizeof (struct queue));
    if (p) p->info = item;
    return p;
}
void addLast(struct queue **q, int item){
    struct queue* p = makenode(item);
    if ((*q)->front == NULL){

        (*q)->front = (*q)->rear = p;
        (*q)->front->next = (*q)->front;
        (*q)->rear->next = (*q)->rear;
    }
    else
    {
        (*q)->rear->next = p;
        p->next = (*q)->front;
        (*q)->rear = p;
    }
}
int delFirst(struct queue **q){

    struct queue *p = (*q)->front;

    if ((*q)->front == 0)
        printf("\nEmpty Queue\n");
    else
    {

        int temp = (*q)->front->info;
        if (((*q)->front->next) != ((*q)->front))
        {
            (*q)->front = (*q)->front->next;
            (*q)->rear->next = (*q)->front;
        }
        else
        {
            (*q)->front = 0;
        }
        return temp;
    }
    free(p);
}
void main()
{
    struct queue *premium, *normal;
    create(&premium);
    create(&normal);
    addLast(&premium, 5);
    addLast(&premium, 10);
    addLast(&normal, 20);
    addLast(&normal, 30);
    printf("%i\n", delFirst(&premium));
    printf("%i\n", delFirst(&premium));
    delFirst(&premium);
    printf("%i\n", delFirst(&normal));
    printf("%i\n", delFirst(&normal));
    delFirst(&normal);
    getch();
}

Is there a better way to do this? I feel that my code is complicated. I am new to C programming and I only learned basics about queues and linked list. I don't know even my code is 100% right or an elegant code.

I compiled this code using DevC++ and it works fine, but when I compile it using MS Visual Studio 2013, it gave me an exception:

  Access violation writing location....

I am very sure my code is not that good.


texts: Sorting by checking 2 distance away elements in a list, and check the method's accuracy

texts:
This code works as follows :
It accepts number of test case T. For each test case, it accepts length of sequence of integers N and the sequence (or list) itself L.

The goal is to sort the list by checking every three consecutive elements, but only comparing the ends. L[i] and L[i+2]. If the right side is less than left one, then these two have to be swapped. This algorithm will continue until nothing can be swapped.

The problem is, my code works for N < 100. Also work for N larger but very slow, exceeded the time limit which is 20 secs.

If the list ended up sorted correctly, the output must be 'OK'.

If the list ended up not sorted, the output must be the first index in which the next index has element less than it.

This is part of google code jam 2018 qualificatiom round, finished already.

How to optimize this in Python..? What are the arguments? Thanks.

    T = input()

    N = []
    L = []
    output = []

    for t in range(T):

        N.append(input())
        L.append(raw_input())

    def trouble(l, n):
        repeat = True
        while repeat:

            repeat = False
            for index in range(0,n-2):
                if l[index] > l[index+2]:
                    repeat = True
                    dum = l[index:index+3]
                    l[index] = dum[-1]
                    l[index+2] = dum[0]
                    del dum
        return l

    def search(l, n):

        for i in range(n):

            if l[i] > l[i+1]:

                return i

    for i in range(T):

        l = L[i].split()
        l = [int(num) for num in l]
        res = trouble(l, N[i])
        if res == sorted(l):
            output.append('OK')
        else:
            output.append(search(l, N[i]))

    for t in range(T):

        print('Case #'+str(t+1)+': '+str(output[t]))