texts: takeWhile, groupBy and group higher order functions

texts:
I'm trying to implement few higher order functions from Haskell in C++. Below are the definitions of takeWhile, groupBy, and group.

I would appreciate it if someone can review and comment if the implementation takes care of all scenarios. Should I be using universal refs for parameters to these functions? Please let me know of any other comments, too. Please assume C++14 standard and above. Also, if there are existing implementations that I can use to study and refer to, please point me to them too.

#include <vector>
#include <utility>

template <typename fwd_iter, typename predicate>
auto takeWhile(fwd_iter first, fwd_iter last, predicate p) -> std::pair<fwd_iter, fwd_iter>
{
    auto till = (first);

    for (; till != last; till++) {
        if (!p(*till)) {
            break;
        }
    }

    return { first, till };
}

// something similar to std::greater or std::less.. is there something for equality??
struct equal {
    template <typename T>
    constexpr bool operator()(const T &lhs, const T &rhs) const
    {
        return lhs == rhs;
    }
};

// predicate type should be : typename *fwd_iter -> typename *fwd_iter  -> bool)
template <typename fwd_iter, typename predicate,
    typename container = std::vector<std::pair<fwd_iter, fwd_iter>>>
auto groupBy(fwd_iter first, fwd_iter last, predicate pred)
{
    auto current = first;
    container ret;

    while (current != last) {
        auto t = takeWhile(current, last, [&](auto x) {return pred(*current, x); });
        current = t.second;
        ret.emplace_back(t);
    }

    return ret;
}

template <typename fwd_iter>
auto group (fwd_iter first, fwd_iter last)
{
    return groupBy(first, last, equal());
}


texts:
I started taking a look at a programming challenge I had read about earlier today on 8thlight. Unfortunately, it seems to have been taken down and all I could remember about it was the problem posed: Given an array of integers, find the maximum sum of contiguous values (a sub-array).

I wanted to tackle the problem from a TDD standpoint rather than diving right in, as the poster had recommended. I didn't see his solution, but what I ended up with was remarkably like Kadane's algorithm, despite having never seen or heard of it until after writing my code and attempting to make this post.

My question is as follows: Is there some extraneous logic in here that could be refactored away? Or perhaps more critically, can you provide any test cases that break this? Some solutions I've seen now that I am searching have special restrictions, such as not being able to work with arrays full of negative numbers, while mine will solve them correctly.

public static int HighestContiguousSum(int[] inputArray)
{
    int currentSum = inputArray[0];
    int bestSum = inputArray[0];

    for (int i = 1; i < inputArray.Length; i++)
    {
      int value = inputArray[i];

      if (bestSum < 0 && bestSum < value)
      {
        bestSum = value;
        currentSum = value;
      }
      else if (value > 0 || (value < 0 && value > -1 * currentSum))
      {
        currentSum += value;
        bestSum = Math.Max(currentSum, bestSum);
      }
      else if (value <= -1 * currentSum)
      {
        currentSum = 0;
      }
    }

    return bestSum;
}

I ended up with ~11 tests, although not all of them are probably required (some were me just trying to break things after the fact to prove to myself it was working).


texts:
I wrote a recursive function to uncheck all menu nodes. It works well, but I need to know if it is right to leave empty block inside if (nodes[i].children.length === 0) base case.

Is there a better design choice?

The function:

function uncheck_all_tree (nodes) {
  var i, n, n_dom_el;

  for (i = 0; i < nodes.length; i++) {
    if (nodes[i].children.length === 0) {
      // recursion bottom;
    } else {
      uncheck_all_tree(nodes[i].children);
    }

    // pop nodes from recursion stack
    n = tree.jstree('get_node', nodes[i]);
    n_dom_el = document.getElementById(n.id + '_anchor');
    if (n_dom_el !== null) {
      console.log(n.id + '_anchor');
      n_dom_el.className = 'jstree-anchor';
    }
    n.state.checked = false;
  }
}


texts: Dynamically allocated C strings in C++, concatenation, pointers, etc

texts:
I'm writing a small Win32 console app that manipulates the contents of binary files. It accepts the filename as a command line parameter and writes to a file named filename.scramble

This is the first time I'm dynamically allocating memory for C strings (which I'm using since the fstream functions use const char*).

I've added the comments to help you understand what I'm trying to do. Please tell me whether I'm doing anything unsafe with pointers or whether I'm allocating memory wrong or any unsafe practice you see regarding dynamically allocating and concatenating C strings in C++. My question is specifically about the strings and the memory management.

#include<iostream>
#include<fstream>
using namespace std;

int main(int argc, char *argv[])
{
    //Program needs at least one extra argument
    //If less, print 'usage'
    if (argc < 2)
        cout<<"usage: "<< argv[0] <<" <filename>\n";

    else
    {
        //Assuming argv[1] is a file name
        fstream fin (argv[1],ios::binary|ios::in);

        if (!fin.is_open())
            cout<<"Could not open file\n";
        else
        {
            //Calculate size of file
            fin.seekg(0,ios::end);
            unsigned long long size = fin.tellg();
            //Find out how many left over characters
            //if using blocks of 16 characters
            int lastset=size%16;
            //Change size to number of blocks
            size /= 16;

            //File name must be <original filename>.scramble
            //Allocate space
            char* name = new char[sizeof(argv[1])+8];

            //Concatenate <original filename>
            strcat_s(name,sizeof(argv[1]),argv[1]);
            //Concatenate ".scramble"
            strcat_s(name,sizeof(argv[1])+8,".scramble");

            fstream fout (name,ios::binary|ios::out);
            //Buffer
            char memblock[16];
            fin.seekg(0,ios::beg);

            //Read from fin and write to fout in blocks of 16 characters
            for(unsigned long long i=0;i<size;++i)
            {
                fin.read(memblock,16);
                /*
                *
                * Manipulation on memblock to be done here
                *
                */
                fout.write(memblock,16);
            }

            //No manipulation for last n bytes, n<16
            fin.read(memblock,lastset);
            fout.write(memblock,lastset);

            fin.close();
            fout.close();

            delete[] name;
        }
    }
    return 0;
}


texts: Breaking group of items into rows then ensure consistent height of each row element

texts:
I'm working on a product category page where the product images have inconsistent heights so I've been asked to improve the page appearance without changing the images.

The page contains x number of products in a 3 column grid.

I decided to set the height of the image wrapper to the height of the image with the maximum height in each row, then use flex to vertically center the images.

How could I improve my JavaScript?

/**
 *  Ensure all rows appear the same height even if they contain products with
 *  small images.
 */

const imgWrappers = Array.from(document.querySelectorAll('.summary-image-wrapper'));
const rows = [];

// 3 Products per row - First group the image wrappers into groups of 3
while (imgWrappers.length !== 0) {
    rows.push({
        elements: imgWrappers.splice(0, 3),
    });
}

// Then establish which element is the tallest in it's group
rows.forEach((row) => {
    let height = 0;

    row.elements.forEach((el) => {
        const currHeight = el.firstElementChild.getAttribute('height');
        height = currHeight > height ? currHeight : height;
    });

    row.height = height;

    // Set the height of each element to that of the tallest element in the row
    row.elements.forEach((el) => {
        el.style.height = `${row.height}px`;
    });
});

Example title

                 POA

EDIT:
I discovered an error within my original code due to string comparison. Take the following row of 3 images and their height:

Image a: 365

Image b: 91

Image c: 401

Given the above images using the code originally given 'image b' will be considered the largest. This is because el.firstElementChild.getAttribute('height') returns a string, when comparing strings javascript does it "alphabetically". This means that js looks at the first character of the string then the second and so on. When comparing two numberic strings if a string starts with a 9 it will always be the largest!

'10000000000' > '9' //false
'89999999999' > '9' //false
'91' > '9' //true

To ensure the original code works the value stored in currHeight needs to be converted to a number e.g currHeight = Number.parseInt(el.firstElementChild.getAttribute('height')); before comparison.


texts: Filter an array of objects by an array in AngularJS

texts:
This code is the whole logic for the AngularJS ui-select lib. I'm not (yet) a JS pro and still learning AngularJS as well but I'm pretty sure this can be done a little more efficient? I'm talking especially about the search: part of the object. In php I would probably do something like array_diff. Any critiques are welcome!

The reason for the selectedIds: [] is that I use ng-repeat to render a list of hidden fields with name="users[]" to be able to fetch the list as a php array on the server side. I'm not suing Angular as a single page app here, I'm just using it for all the widgets but the data itself is submitted with the whole page as POST.

The for (var key in result.data) is done to filter already selected ids out of the array. It was the most easy solution to avoid the error Duplicates in a repeater are not allowed.. Sure I could pass the already existing ids to the lookup GET request but I think this works fine on the client side as well.

$scope.usersList = {
    items: [],
    selected: [],
    selectedIds: [],
    extractIds: function() {
        $scope.usersList.selectedIds = [];
        for (var i = 0; i < $scope.usersList.selected.length; i++) {
            $scope.usersList.selectedIds.push($scope.usersList.selected[i].id);
        }
    },
    select: function($item, $model) {
        this.extractIds();
    },
    remove: function($item, $model) {
        this.extractIds();
    },
    search: function(term) {
        if (term.length > 2) {
            UsersService.lookup(term).then(function(result) {
                for (var key in result.data) {
                    if (result.data.hasOwnProperty(key)) {
                        if ($scope.usersList.selectedIds.indexOf(result.data[key].id) != -1) {
                            delete result.data[key];
                        };
                    }
                }
                $scope.usersList.items = result.data;
            });
        }
    }
};


texts:
I've just encountered this question and am trying to solve it using Java.

Here is my solution to it, which may not be optimized or might not be right way to do it. Someone please review whether it is correct or there is some good way to do it. For focusing on logic, I have hard coded List creation and code repetition is present.

package linkedlist.singly;

//Add two numbers represented by linked lists
// 245   :  5 -> 4 -> 2
// 99789 :  9 -> 8 -> 7 -> 9 -> 9
// Ans   :  99341
public class Add2NumbersInLinkListType2 {

    static int carry=0;

    public static void main(String[] args) {

        Node templ11 = new Node(5);
        Node templ12 = new Node(4);
        Node templ13 = new Node(2);

        Node templ21 = new Node(9);
        Node templ22 = new Node(8);
        Node templ23 = new Node(7);
        Node templ24 = new Node(9);
        Node templ25 = new Node(9);

        templ11.setNext(templ12);
        templ12.setNext(templ13);

        templ21.setNext(templ22);
        templ22.setNext(templ23);
        templ23.setNext(templ24);
        templ24.setNext(templ25);

        Node res = findSum(templ11, templ21, 0);
        if(carry==1){
            Node tempNode = new Node(carry);
            tempNode.setNext(res);
            res = tempNode;
        }
        while(res!=null){
            System.out.print(res.getData());
            res=res.getNext();
        }
    }

    private static Node findSum(Node l1, Node l2, int diff){

        int length1 = findLength(l1);
        int length2 = findLength(l2);

        if(length1>length2){
            //l1 having more nodes
            Node res = findSum(l1.getNext(), l2, diff--);
            int data = l1.getData() + carry;
            if(data>9){
                carry=1;
                Node tempNode = new Node(data%10);
                tempNode.setNext(res);
                res = tempNode;
            }else{
                carry=0;
                Node tempNode = new Node(data);
                tempNode.setNext(res);
                res = tempNode;
            }
            return res;

        }else if(length2>length1){
            //l2 having more nodes
            Node res = findSum(l1, l2.getNext(), diff++);
            int data = l2.getData() + carry;
            if(data>9){
                carry=1;
                Node tempNode = new Node(data%10);
                tempNode.setNext(res);
                res = tempNode;
            }else{
                carry=0;
                Node tempNode = new Node(data);
                tempNode.setNext(res);
                res = tempNode;
            }
            return res;

        }else{
            //both have same length
            Node res = findSumForListOfSameSize(l1, l2);
            return res;
        }
    }

    private static Node findSumForListOfSameSize(Node l1, Node l2){
        if(l1==null && l2==null)
            return null;

        Node head = findSumForListOfSameSize(l1.getNext(), l2.getNext());

        int temp = l1.getData() + l2.getData() + carry;
        if(temp>9){
            carry=1;
        }else{
            carry=0;
        }

        if(head==null){
            head = new Node(temp % 10);
        }else{
            Node tempNode = new Node(temp % 10);
            tempNode.setNext(head);
            head = tempNode;
        }
        return head;
    }

    private static int findLength(Node node){
        int count=0;
        while(node!=null){
            count++;
            node = node.getNext();
        }
        return count;
    }
}


texts: Scrape a jobs board and keep persistent record

texts:
I'm trying to improve my pretty basic coding skills, and I've written this program to scrape a jobs board (I'd ultimately add several) and put the data in a db file with SQLITE3. The code works, but I can't help feeling that there are some simple things I might have done more gracefully.

One error I know about is that I don't have a primary key for my DB. I'm going to add this! In the meantime, I've just been querying the DB with something like
SELECT DISTINCT Title, Company FROM jobs WHERE Date BETWEEN datetime('now', '-3 days') AND datetime('now', 'localtime'); which works nicely.

Thanks in advance for any feedback!

import csv
import datetime
import urllib.request
import sqlite3
from sqlite3 import Error
from bs4 import BeautifulSoup
from dateutil import parser

"""
Scrapes STA jobs board, adds new jobs into a database
"""

def update_db():
    try:
        conn = sqlite3.connect('jobs.db')
        c = conn.cursor()

        # call the scraping functions
        soup = scrape_secret()
        jobs = clean_jobs(soup)
        result = organise(jobs)
        final = data_cleanser(result)
        export(final)

        # after exporting to csv (just in case) we delete the title row and convert nested lists to tuples
        del final[0]
        new_result = [tuple(l) for l in final]
        # only necessary once
        # c.execute('''CREATE TABLE jobs (Title, Company, Location, Type, Date Posted)''')

        c.executemany("INSERT INTO jobs VALUES (?,?,?,?,?)", new_result)
        conn.commit()
        conn.close()

    except Error as e:
        print(e)

# function to remove multiple occurrences of one term ('new')
def remove_value_from_list(the_list, val):
    return [value for value in the_list if value != val]

def length_enforcer(the_list, length):
    return [value for value in the_list if len(value) == length]

# hit the website and scrape the first page
def scrape_secret():
    url = "https://jobs.secrettelaviv.com/"
    req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
    page = urllib.request.urlopen(req)
    return BeautifulSoup(page, "html.parser")

def clean_jobs(soup):
    # jobs are in 'spans'
    all_spans = soup.find_all("span")
    jobs = []
    for span in all_spans:
        jobs.append(span.get_text().strip())
    # remove extraneous elements
    jobs.remove('')
    jobs.remove('Subscribe to our EVENTS Newsletter')
    jobs.remove('Join our facebook GROUP')
    jobs = remove_value_from_list(jobs, '')
    return remove_value_from_list(jobs, 'new')

def organise(jobs):
    # make list of lists
    result = [["Title", "Company", "Location", "Duplicate", "Type", "Date Posted"]]
    new_list = []
    for job in jobs:
        if len(new_list) == 6:
            a = list(new_list)
            result.append(a)
            new_list = [job]
        else:
            new_list.append(job)
    result.append(new_list)
    return length_enforcer(result, 6)

def data_cleanser(result):
    for i in result:
        del i[3]
        try:
            i[4] = parser.parse(i[4])
        except ValueError:
            pass
    return result

def export(result):
    csvfile = "secret_today" + datetime.datetime.today().strftime('%m-%d') + ".csv"
    with open(csvfile, "w") as output:
        writer = csv.writer(output, lineterminator='\n')
        writer.writerows(result)

if __name__ == '__main__':
    update_db()


texts:
I'm trying to get my Quicksort implementation doing fewer comparisons. The first element is used as a pivot. Could you give me some directions if there are any places that should be optimized in a sense of making fewer comparisons? As I understand, it's due to a redundant recursion pass, since the partition subroutine and comparisons counting in it are implemented correctly.

#include <vector>

using namespace std;
using uint = unsigned int;

uint PartitionSub(vector<uint>& inp, uint l, uint r, uint& numOfCmp);

void QuickSort(vector<uint>& inp, uint l, uint r, uint& numOfCmp)
{
    if (r - l < 2)
        return;

    uint newPivotIdx = PartitionSub(inp, l, r, numOfCmp);

    QuickSort(inp, l, newPivotIdx, numOfCmp);
    QuickSort(inp, newPivotIdx + 1, r, numOfCmp);
}

uint PartitionSub(vector<uint>& inp, uint l, uint r, uint& numOfCmp)
{
    auto swap = [&inp](uint a, uint b)
    {
        uint buf = inp[a];
        inp[a] = inp[b];
        inp[b] = buf;
    };

    //numOfCmp += r - l; // we can use this, but ++numOfCmp just before
                         // comparison is more clear
    uint i = l + 1;
    uint j = l + 1;

    uint p = inp[l];

    for (; j <= r; j++)
    {
        ++numOfCmp;
        if (inp[j] <= p)
        {
            if (i != j)
                swap(i, j);
            i++;
        }
    }

    uint newPivotIdx = i - 1;
    swap(l, newPivotIdx);
    return newPivotIdx;
}


texts: Generic Adapter with search and sort functionality

texts:
I have tried to create a GenericAdapter that can help you search, sort automatically without writing a lot of code.

But in order to use this you have to follow some rules. How can I make it better and where am I not using a better approach.

rules for using GenericAdapter.

extends your business model with BaseModel
extends your viewHolder with BaseViewHolder
your adapter must extends GenericAdapter

where

BaseModel.class

public abstract class BaseModel<T> implements Comparator<T>
{
   public abstract String getAttributeToSearch();
   ///public abstract int whatYouWantToCompare();
}

BaseViewHolder.class

public abstract class BaseViewHolder<T extends BaseModel> extends RecyclerView.ViewHolder
{

  public BaseViewHolder(View itemView) {
    super(itemView);
  }

  public abstract void bindData(T data);
}

GenericBaseAdapter.class

public abstract class GenericBaseAdapter<T extends BaseModel, U extends BaseViewHolder> extends RecyclerView.Adapter<U> implements Filterable {

    private Context mContext;
    private List<T> itemList;
    private List<T> origList;

    public GenericBaseAdapter(Context mContext, List<T> itemList) {
        this.mContext = mContext;
        this.itemList = itemList;
        this.origList = itemList;
    }

    @Override
    public void onBindViewHolder(U holder, int position) {
        holder.bindData(itemList.get(position));
    }

    @Override
    public int getItemCount() {
        return itemList.size();
    }

    public T getItem(int position) {
        return itemList.get(position);
    }

    public void setItems(List<T> itemList) {
        this.itemList = itemList;
        this.origList = itemList;
        notifyDataSetChanged();
    }

    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                final FilterResults oReturn = new FilterResults();
                final ArrayList<T> results = new ArrayList<>();
                if (origList == null)
                    origList = new ArrayList<>(itemList);
                if (constraint != null && constraint.length() > 0) {
                    if (origList != null && origList.size() > 0) {
                        for (final T cd : origList) {
                            if (cd.getAttributeToSearch().toLowerCase()
                                    .contains(constraint.toString().toLowerCase()))
                                results.add(cd);
                        }
                    }
                    oReturn.values = results;
                    oReturn.count = results.size();//newly Aded by ZA
                } else {
                    oReturn.values = origList;
                    oReturn.count = origList.size();//newly added by ZA
                }
                return oReturn;
            }

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(final CharSequence constraint,
                                          FilterResults results) {
                itemList = new ArrayList<>((ArrayList<T>) results.values);
                // FIXME: 8/16/2017 implement Comparable with sort below
                ///Collections.sort(itemList);
                notifyDataSetChanged();
            }
        };
    }

    public void sortItems(T obje) {
        Collections.sort(itemList, obje);
        notifyDataSetChanged();
    }
}

for sorting use

mAdapter.sortItems(productList.get(0));

for searching..

mAdapter.getFilter().filter("any string to search");


texts:
The following was posted on PPCG:

  Your job is to create the slowest growing function you can in no more than 100 bytes.

I did some Googling, and I was interested in the Inverse Ackermann Function:

$$
\alpha(m,n) = \min\{i \ge 1 : A(i, \lfloor \frac{m}{n} \rfloor \ge \log_2n\}
$$

Where \$A\$ is the Ackermann Function:

$$
A(m,n) =
\begin{cases}
n + 1, & \text{if} \space m = 0 \\
A(m - 1, 1) & \text{if} \space m > 0 \space \text{and} \space n = 0 \\
A(m - 1, A(m, n - 1)) & \text{if} \space m > 0 \space \text{and} \space n \gt 0
\end{cases}
$$

The Ackermann function itself is not too difficult to implement. Here is my implementation:

A=(m,n)=>m?A(m-1,n?A(m,n-1):1):n+1

However, the mathematical stuff in the Inverse Ackermann stumped me. I came up with the following, also changing it from two variables to one:

a=(m,n=m,i=1)=>{while(A(i,m/n|0)<=Math.log2(n))i++;return i}

However, that was yesterday. Today, I'm pretty sure I screwed some stuff up. i will always be one more than it should be, since the loop increments and then checks. So, the code should be this:

a=(m,n=m,i=1)=>{while(A(i,m/n|0)<=Math.log2(n))i++;return i-1}

Now, of course this will StackOverflow very quickly. However, theoretically, it works.

Readable:

function Ackermann(m, n) {
  return m ? Ackermann(m - 1, n ? Ackermann(m, n - 1) : 1) : n + 1;
}

function inverseAckermann(m) {
  var n = m;
  var i = 1;

  while (Ackermann(i, Math.floor(m / n)) <= Math.log2(n)) {
    i++;
  }

  return i - 1;
}

Any improvements to the implementation of the inverse Ackermann would be appreciated. I really wanted to use Math.min but I could not figure how to.

Note: I know this can be golfed more, and I know I can slow it down more. I'm more interested in my algorithm than scoring well in the challenge. Don't worry about keeping your suggestions/improvements golfed either :)


texts: Checking if a multi dimensional array's given property is empty or not for the whole collection

texts:
This is what I am doing and it's working:

var isEmpty = true;
for(let i = 0; i< members.length; i++)
{
    var member = members[i];
    if(member && member[3]){
        isEmpty = false;
        break;
    }
}

if(isEmpty) {
    var somePrefix = "123 -"
    for(let i = 0; i< members.length; i++)
    {
        var member = members[i];
        if(member && member[2]){
            member[3] = somePrefix + i;
        }
    }
}

Can this be improved? I'm simply checking if a specific property is empty for all of the collection of multi dimensional array.

Here is what's happening:

Checking X property is empty for all members
If it is, then auto populate it

If any of the property is filled in then leave it as is


texts:
I've written a class to make async SQL calls and it appears to work like a charm! But I'm a bit concerned about what it means to send a lot of queries to the server and then aborting them by throwing an abort exception on the calling thread. Is this a problem?

The code also launches a lot of threads.  Is there any downside to this? Should I use ThreadPool instead, and if so, how?

I'm using .NET 4.

//Class for asynchronous SQL calls
public class SqlAsync
{
    private Thread LastAction { get; set; }
    private string ConnectionString { get; set; }
    public int Timeout { get; set; }

    public SqlAsync(string connstring)
    {
        this.ConnectionString = connstring;
        this.Timeout = 30;
    }

    public void AsyncSqlCall<T>(string sp, Action<T> Callback, Func<SqlDataReader, T> HandleResult, Dictionary<string, object> Params = null)
    {
        TryKillThread(this.LastAction);

        this.LastAction = new Thread(() =>
        {
            T returnobj;
            using (SqlConnection conn = new SqlConnection(this.ConnectionString))
            using (SqlCommand cmd = new SqlCommand(sp, conn))
            {
                cmd.CommandTimeout = this.Timeout;
                cmd.CommandType = CommandType.StoredProcedure;
                if (Params != null)
                {
                    foreach (KeyValuePair<string, object> kvp in Params)
                    {
                        cmd.Parameters.AddWithValue(kvp.Key, kvp.Value ?? DBNull.Value);
                    }
                }
                conn.Open();
                using (SqlDataReader rdr = cmd.ExecuteReader())
                {
                    returnobj = HandleResult(rdr);
                    rdr.Close();
                }
                conn.Close();
            }
            new Thread(() => Callback(returnobj)).Start();
        });
        this.LastAction.Start();
    }

    private void TryKillThread(Thread thread)
    {
        if (thread != null && thread.IsAlive)
        {
            try
            {
                thread.Abort();
            }
            catch (ThreadStateException)
            { /*If thread ends between IsAlive check and Abort call, then just ignore*/ }
        }
    }
}

This is an example of how I use the class

public class Example : Form
{
    DbExample DbEx = new DbExample("");
    public void tbExample_TextChanged(object sender, EventArgs e)
    {
        DbEx.BeginGetSomething(tbExample.Text, BindDgvSomething);
    }
    private void BindDgvSomething(DataTable dt)
    {
        dgvSomething.Invoke(new Action(() => dgvSomething.DataSource = dt));
    }
}

public class DbExample
{
    private SqlAsync SqlAsync;
    private string Connstr;

    public DbExample(string connstr)
    {
        this.Connstr = connstr;
        this.SqlAsync = new SqlAsync(this.Connstr);
    }
    private DataTable LoadReader(SqlDataReader rdr)
    {
        DataTable dt = new DataTable();
        dt.Load(rdr);
        return dt;
    }
    public void BeginGetSomething(string name, Action<DataTable> Callback)
    {
        Dictionary<string, object> Params = new Dictionary<string, object>()
        {
            { "@Name", name }
        };

        SqlAsync.AsyncSqlCall("spGetSomething", Callback, LoadReader, Params);
    }
}


texts:
In a different post I showed the following Perl CGI script. Someone in the comments said that

  "You're using a lot of very unperlish syntax, and I'd like to give you some feedback".

So, here it is, and tell me how to make it more Perlish?  I came from a C background so I'm all ears (or eyes)!

#!/usr/bin/perl -T

use strict;
use warnings;
use CGI qw/:all/;

my $basepath = '/some/path/to';
my $f = param("f") || '';

($f eq '') && die;

my $path = "$basepath/$f.pdf";

open(PATH, "<$path") || die;
binmode PATH;

print header(-type => "application/pdf",
         -target => "$f");
print;

while (<PATH>) {
    print($_);
}
close(PATH);


texts:
Given a matrix, clockwise rotate elements in it.
Examples:

Input
1    2    3
4    5    6
7    8    9

Output:
4    1    2
7    5    3
8    9    6

Input:
1    2    3    4
5    6    7    8
9    10   11   12
13   14   15   16

Output:
5    1    2    3
9    10   6    4
13   11   7    8
14   15   16   12

Scala Implementation is below. I do feel that I do not need to have a rotatedMatrix predefined (which I am filling with -1) and I can build it up during my recursive calls, but I am not able to do it.
Thanks in advance for helping me on this.

import scala.util.Random

object MatrixRotate extends App {

  def getCol(c: Int, m: Array[Array[Int]]): Seq[Int] = (0 to (m(0).length - 1)) map ( r => m(r)(c))
  def getRow(r: Int, m: Array[Array[Int]]): Seq[Int] = m(r).toSeq
  def innerMatrix(m: Array[Array[Int]]): Array[Array[Int]] = {
    if (m.length == 0) Array.empty
    else {
      val rows = m.length - 1
      val cols = m(0).length - 1

      (1 until rows).map { r =>
        (1 until cols).map { c =>
          m(r)(c)
        }.toArray
      }.toArray
    }
  }

  val rotatedMatrix = Array.fill(6)(Array.fill(6)(-1))
  def rotateByOne(m: Array[Array[Int]], startRow: Int, startCol: Int,
                  endRow: Int, endCol: Int): Unit = {
    m.size match {
      case 0 =>
      case _ =>
        getRow(0, m) match {
          case Nil =>
          case x => x.init.zipWithIndex foreach { case (e, index) => rotatedMatrix(startRow)(startCol+index+1) = e }
        }
        getCol(m(0).length - 1, m) match {
          case Nil =>
          case x => x.init.zipWithIndex foreach { case (e, index) =>  rotatedMatrix(startRow+index+1)(endCol) = e }
        }
        getRow(m.length - 1, m) match {
          case x :: Nil =>
          case x => x.tail.zipWithIndex foreach { case (e, index) => rotatedMatrix(endRow)(startCol+index) = e }
        }
        getCol(0, m) match {
          case x :: Nil =>
          case x => x.tail.zipWithIndex foreach { case (e, index) => rotatedMatrix(startRow+index)(startCol) = e }
        }
        rotateByOne(innerMatrix(m), startRow + 1, startCol + 1, endRow - 1, endCol - 1)
    }

  }

  val matrix = Array.fill(6)(Array.fill(6)(Random.nextInt(100)))
  matrix foreach(row => println(row.mkString(",")))

  println("----------")

  rotateByOne(matrix, 0, 0, 5, 5)
  rotatedMatrix foreach (row => println(row.mkString(",")))
}

Update

I realize that this code seems to be failing for rectangular matrix. I still need to solve it for that case.


texts:
There are N gas stations along a circular route, where the amount of
  gas at station i is gas[i].

  You have a car with an unlimited gas tank and it costs cost[i] of gas
  to travel from station i to its next station (i+1). You begin the
  journey with an empty tank at one of the gas stations.

  Return the starting gas station's index if you can travel around the
  circuit once in the clockwise direction, otherwise return -1.

  Note:

  If there exists a solution, it is guaranteed to be unique. Both input
  arrays are non-empty and have the same length. Each element in the
  input arrays is a non-negative integer. Example 1:

  Input:  gas  = [1,2,3,4,5] cost = [3,4,5,1,2]

  Output: 3

  Explanation: Start at station 3 (index 3) and fill up with 4 unit of
  gas. Your tank = 0 + 4 = 4 Travel to station 4. Your tank = 4 - 1 + 5
  = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to
  travel back to station 3. Therefore, return 3 as the starting index.
  Example 2:

  Input:  gas  = [2,3,4] cost = [3,4,3]

  Output: -1

  Explanation: You can't start at station 0 or 1, as there is not enough
  gas to travel to the next station. Let's start at station 2 and fill
  up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 0. Your
  tank = 4 - 3 + 2 = 3 Travel to station 1. Your tank = 3 - 3 + 3 = 3
  You cannot travel back to station 2, as it requires 4 unit of gas but
  you only have 3. Therefore, you can't travel around the circuit once
  no matter where you start.

Here is my solution:

public class Solution {
    public int CanCompleteCircuit(int[] gas, int[] cost) {
        int startIndex = 0;
        int tank = 0;
        int diff= 0;
        int sum =0;
        for(int i=0;i < gas.Length; i++)
        {
            diff = gas[i] - cost[i];
            sum += diff;
            if(tank + diff < 0)
            {
                startIndex = i+1;
                tank = 0;
            }
            else
            {
                tank += diff;
            }
        }
        if(sum < 0)
        {
            return -1;
        }
        else
        {
            return startIndex;
        }
    }
}

Please review code runtime and memory. Any other comments are welcome!


texts: PL/pgSQL function to test if a word is contained within a phrase

texts:
I am using PostgreSQL 11.0 and I wrote a PL/pgSQL function to test if a word or phrase is contained within another phrase. This function is called several times within another function to extract some words from a paragraph. The execution of the calling function is slow, and I suspect it is because of this function:

CREATE OR REPLACE FUNCTION public."Contains"(
p_text1 character varying,
p_text2 character varying)
RETURNS boolean
LANGUAGE 'plpgsql'

COST 100
immutable
AS $BODY$
declare

v_res integer := 0;

BEGIN

p_text2:= replace(p_text2, '(','\(');
p_text2:= replace(p_text2, ')','\)');

perform 1
where   ( p_text1 similar to '((% )|(%-)|(%\())*'||p_text2||'(( %)|(-%)|(\)%))*' ) or
    ( replace(p_text1,'-',' ') similar to '((% )|(%\())*'||replace(p_text2,'-',' ')||'(( %)|(\)%))*' ) or
    ( replace(p_text1,'-','') similar to '((% )|(%\())*'||replace(p_text2,'-','')||'(( %)|(\)%))*' );

return found;

END;
$BODY$;

Words (or phrase) boundaries could be spaces (' word '), dashes ('-word-'), parentheses ('(word)') or nothing (like when the word is at the beginning or the end of the phrase).

For example:

select public."Contains"('domain-specific ontology' , 'domain'); -- true
select public."Contains"('domain-specific ontology' , 'ontology'); -- true
select public."Contains"('domain-specific ontology' , 'domain specific'); -- true
select public."Contains"('domain-specific ontology' , 'domain-specific'); -- true
select public."Contains"('information retrieval (IR)' , 'IR'); -- true
select public."Contains"('information retrieval (IR)' , 'information retrieval IR'); -- false
select public."Contains"('domain-specific ontology' , 'domain ontology'); -- false

This function is called in the outer function this way:

perform 1
         from some_table
         where public."Contains"(col1, v_word) = true;

some_table has no index on col1.

So, is there a faster alternative to the SIMILAR TO operator to perform the same regular expression matching?


texts: Cut excess whitespace from input and print to output

texts:
Title is pretty self explanatory, this program just takes in input (not from command line arguments), removes the extra spaces in the input, then prints that to output.

/*replace string of blanks with single blank*/

#include "stdio.h"

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

    int nb,c = 0;

    while ((c=getchar()) != EOF){

           if (c == ' ' || c == '\n' || c == '\t')

                 if (nb >= 1)

                    nb = nb + 1;

                 else
                    nb = 1;
           else

                nb = 0;
        if (nb <= 1)
            putchar(c);

    }
    return 0;
}

Any suggestions on how to improve it?


texts:
Working with currencies I am aware it is not good to work with floating point values due to rounding and maintaining precision. Better is to work with integers. Would the following Currency class make sense, where an amount is defined as an instance of Currency and converted to cents.

class Currency():

    def __init__(self, value):
        self._cents = int(round(value*100,0))

    def __add__(self, other):
        return self.__class__((self._cents + other._cents)/100)

    def __sub__(self, other):
        return self.__class__((self._cents - other._cents)/100)

    def __mul__(self, factor):
        if type(factor) not in [int, float]:
            raise ValueError('factor must be a scalar')

        return self.__class__(factor * self._cents / 100)

    def __rmul__(self, factor):
        if type(factor) not in [int, float]:
            raise ValueError('factor must be a scalar')

        return self.__class__(factor * self._cents / 100)

    def __truediv__(self, divisor):
        if type(divisor) not in [int, float]:
            raise ValueError('divisor must be a scalar')

        if divisor != 0:
            return self.__class__(self._cents / divisor / 100)
        else:
            raise ValueError('Cannot divide by zero')

    def __repr__(self):
        return str(f'{self._cents/100:,.2f}')

    def __str__(self):
        return str(f'{self._cents/100:,.2f}')

    @property
    def dollars(self):
        return self._cents / 100

    @property
    def cents(self):
        return self._cents

Some results

>>> from money import Currency
>>> a = Currency(100)
>>> b = Currency(0.01)
>>> a+b
100.01
>>> a*2
200.00
>>> a/2
50.00
>>> 2*a
200.00
>>> total = Currency(0)
>>> for i in range(10_000_000):
...     total += b
...
>>> total
100,000.00
>>> a.dollars
100.0
>>> b.cents
1
>>>
```


texts: Optimizing multiple if-else from static class with LINQ

texts:
I have a static class:

public static class ConfigurationDetails
{
    public static string SharepointServer { get; set; }
    public static string Username { get; set; }
    public static string Password { get; set; }
    public static string SharepointDomain { get; set; }
    public static string ServiceLibrary { get; set; }
    public static string SqlServer { get; set; }
    public static string SQLUsername { get; set; }
    public static string SQLPassword { get; set; }
    public static string SQLDomain { get; set; }
}

which needs to be updated from the values of a dictionary.

Using if the code is below:

var configValues = ReadConfiguration();

if (configValues.ContainsKey("SharepointServer"))
{
    ConfigurationDetails.SharepointServer = configValues["SharepointServer"];

}
if (configValues.ContainsKey("ServiceLibrary"))
{
    ConfigurationDetails.ServiceLibrary = configValues["ServiceLibrary"];

}
if (configValues.ContainsKey("Username"))
{
    ConfigurationDetails.Username = configValues["Username"];

}
if (configValues.ContainsKey("Password"))
{
    ConfigurationDetails.Password= configValues["Password"];

}

Now this will do the job, but there would be a lot of ifs. I've tried with LINQ, but this is the closest I've gotten:

configValues.Where(kv => kv.Key == "SharepointServer").ToList().ForEach(kv => ConfigurationDetails.SharepointServer = kv.Value);

and it's not doing any good. Any other ideas, please?


texts: Opening files using fopen only if user enters correct password

texts:
I wrote this program to just get some practice in C, but I have a question:

Do you see anything that I am doing that will create bad habits in my future programming?

#include <stdio.h>

char password[]="ps"; // set the password that user must match
char input[20];          // user input buffer
char filename[32];
FILE *fp;
int c,i,count=3;

int main()
{

printf("Please enter the password:");   //ask for password
fgets(input,20,stdin);                  //store user entry into input buffer
sscanf(input,"%s",input);               //format

    if(strcmp(password,input)==0)   //if the input is equal to the password then open the file and print contents
    {
            if((fp=fopen("text","r")) != NULL)
            {
                    while((c=getc(fp)) != EOF)
                    {
                            putchar(c);
                    }
                    fclose(fp);                     //close the file once done
            }
            else
            {
                    perror("Error:");
                    return(-1);
            }
    }
    else if(strcmp(password,input) != 0)    //if the input is wrong then give the user 3 more tries
         {
                    for(i=0;i<3;i++)
                    {
                            printf("\nThe password you entered is incorrect!");
                            printf("\n%d tries left, password:",count);
                            fgets(input,20,stdin);
                            sscanf(input,"%s",input);

                            --count;

                            if(strcmp(password,input)==0)   //if out of those 3 tries entry is correct--open file/print contents
                            {
                                    if((fp=fopen("text","r")) != NULL)
                                    {
                                            while((c=getc(fp)) !=EOF)
                                     {
                                                    putchar(c);
                                            }
                                            fclose(fp);     //close file
                                            break;          //break out of for loop
                                    }
                                    else
                                    {
                                            perror("Error:");
                                            return(-1);
                                    }
                            }
                    }
            }
}


texts: Template with boost::operators extremely verbose and repeating

texts:
I got the following ugly code:

template < class _Coeff,
       unsigned _nVars,
       typename _Expo=int,
       template <class, class> class _Map = _Map >
class Polynomial
      : boost::ring_operators< Polynomial<_Coeff,_nVars,_Expo,_Map>
      , boost::addable       < Polynomial<_Coeff,_nVars,_Expo,_Map>, _Coeff
      , boost::addable       < Polynomial<_Coeff,_nVars,_Expo,_Map>,
                   std::pair< std::array<_Expo,_nVars>, _Coeff >
      , boost::subtractable  < Polynomial<_Coeff,_nVars,_Expo,_Map>, _Coeff
      , boost::subtractable  < Polynomial<_Coeff,_nVars,_Expo,_Map>,
                   std::pair< std::array<_Expo,_nVars>, _Coeff >
      , boost::multipliable  < Polynomial<_Coeff,_nVars,_Expo,_Map>, _Coeff
      , boost::multipliable  < Polynomial<_Coeff,_nVars,_Expo,_Map>,
                   std::pair< std::array<_Expo,_nVars>,_Coeff >
                > > > > > > > {

In particular, I hate to repeat Polynomial<_Coeff,_nVars,_Expo,_Map>. Is there a way to improve this syntax without using the preprocessor ? I can't manage to get any help from the using keyword here.

Just for the infos: I'm writing multivariate polynomials where _Coeff is the class of the coefficients and the terms X1^4x2^4 are represented as std::array<_Expo,_nVars>.


texts:
I've been trying to get better at Haskell for a while, and have recently been working on a lot of small projects with it. This constructs a binary decision tree.

The command to run it is:

stack exec decision-tree-exe <threshold> <training file> <testing file>

where threshold is in the range (0,1].

I think I've gotten a lot better, but I'm still having problems, especially with performance and readability. For this project, I took a more top down approach, implementing functions after using them. src/DecisionTree.hs is where the bulk of the logic is, and the file is pretty much in order of writing. I would love to get some feedback from some more experienced people on where I might improve.

module DecisionTree where

import Data.List (genericLength, maximumBy, nub)
import Data.Map (elemAt, foldlWithKey', fromListWith)
import Data.Ord

data DecisionTree a b
  = Node ([a] -> Bool) (DecisionTree a b) (DecisionTree a b)
  | Leaf b

type Dataset cat attrs = [(cat, [attrs])]

type Threshold = Double

type Splitter c a = ([a] -> Bool, Dataset c a, Dataset c a)

apply :: DecisionTree a b -> [a] -> b
apply (Leaf b) _ = b
apply (Node f l r) a =
  case f a of
    False -> apply l a
    True -> apply r a

train ::
     (Ord c)
  => (Dataset c a -> Maybe (Splitter c a))
  -> Dataset c a
  -> DecisionTree a c
train splitter dataset =
  case splitter dataset of
    Just (partitioner, left, right) ->
      Node partitioner (train splitter left) (train splitter right)
    Nothing -> Leaf majority
  where
    classCounts = fromListWith (+) $ map (\k -> (fst k, 1)) dataset
    majority = fst $ foldlWithKey' max (elemAt 0 classCounts) classCounts
    max acc k v
      | v > snd acc = (k, v)
      | otherwise = acc

giniSplitter ::
     (Ord a, Ord c) => Threshold -> Dataset c a -> Maybe (Splitter c a)
giniSplitter threshold dataset =
  case fst maxDelta > threshold of
    True -> Just $ snd maxDelta
    False -> Nothing
  where
    attrs = nub . concat . snd . unzip $ dataset
    partitioner a = (a `elem`)
    delta a = giniDelta (partitioner a) dataset
    maxDelta = maximumBy (comparing fst) $ map delta attrs

giniDelta :: (Eq c) => ([a] -> Bool) -> Dataset c a -> (Double, Splitter c a)
giniDelta partitioner dataset =
  ( gini dataset - (d1 / d * gini left + d2 / d * gini right)
  , (partitioner, left, right))
  where
    left = filter (not . partitioner . snd) dataset
    right = filter (partitioner . snd) dataset
    d1 = genericLength left
    d2 = genericLength right
    d = genericLength dataset

gini :: (Eq c) => Dataset c a -> Double
gini d = 1 - sum [(pj c) ** 2 | c <- nub . fst . unzip $ d]
  where
    pj c = genericLength (filter ((== c) . fst) d) / genericLength d


texts: SPOJ GSS1 challenge (maximum subarray sum) using Java

texts:
The problem is presented here as follows:

  You are given a sequence A[1], A[2], ..., A[N] . ( |A[i]| ≤ 15007 , 1
  ≤ N ≤ 50000 ). A query is defined as follows:  Query(x,y) = Max {
  a[i]+a[i+1]+...+a[j] ; x ≤ i ≤ j ≤ y }.  Given \$M\$ queries, your program
  must output the results of these queries.

  Input

  The first line of the input file contains the integer \$N\$.
  In the second line, \$N\$ numbers follow.
  The third line contains the integer \$M\$.
  \$M\$ lines follow, where line \$i\$ contains 2 numbers \$x_i\$ and \$y_i\$.

  Output

  Your program should output the results of the \$M\$ queries, one query per
  line.

  Example

  Input:

  3

  -1 2 3

  1
  1 2

  Output:

  2

I am using a segment tree and getting a TLE after test case 10:

import java.util.*;
import java.io.*;

public class Solution{

static void segTree(int[] arr, int[] seg, int low, int high, int pos){

    if(high == low){
        seg[pos] = arr[low];
        return;
    }

    int mid = (high + low) / 2;

    segTree(arr, seg, low, mid, 2 * pos + 1);
    segTree(arr, seg, mid + 1, high, 2 * pos + 2);
    int sum = seg[2 * pos + 1]+seg[2 * pos + 2];
    int temp = Math.max(seg[2 * pos + 1], seg[2 * pos + 2]);
    seg[pos] = Math.max(temp, sum);
}

static int sumMax(int[] seg, int qlow, int qhigh, int low, int high, int pos){

    if(qlow <= low && qhigh >= high)
        return seg[pos];

    if(qlow >= high || qhigh <= low)
        return Integer.MIN_VALUE;

    int mid = (low+high) / 2;

    return Math.max(sumMax(seg, qlow, qhigh, low, mid, 2*pos+1), sumMax(seg, qlow, qhigh, mid+1, high, 2*pos+2));
}

static class FastScanner implements Closeable {
BufferedReader in;
StringTokenizer st;
FastScanner() throws IOException {
    in = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws IOException {
    while (st == null || !st.hasMoreTokens()) {
        String line = in.readLine();
        if (line == null) {
            return null;
        }
        st = new StringTokenizer(line);
    }
    return st.nextToken();
}
int nextInt() throws IOException {
    return Integer.parseInt(next());
}
public void close() throws IOException {
    in.close();
    st = null;
}
}

public static void main(String[] args) throws IOException {
    try(FastScanner sc = new FastScanner();
        PrintWriter out = new PrintWriter(System.out)){

            int n = sc.nextInt();
            int[] arr = new int[n];

            int size = (int)Math.ceil(Math.log(arr.length)/Math.log(2)) + 1;

            int seg_size = (int)Math.pow(2, size) - 1;
            int[] seg = new int[seg_size];
            Arrays.fill(seg, Integer.MIN_VALUE);

            for(int i = 0; i < n; i++)
                arr[i] = sc.nextInt();

            segTree(arr, seg, 0, arr.length - 1, 0);

            int m = sc.nextInt();
            while(m-- > 0){
                int i = sc.nextInt();
                int j = sc.nextInt();
                i--;j--;
                out.println(sumMax(seg, i, j, 0, arr.length - 1, 0));
            }

        }
    }
 }


texts: JavaScript nesting XMLHttp requests and in a loop

texts:
I am new to JavaScript, especially the wonders of async and closures and would like some help on the attached code. It is in a Chrome extension and retrieves a list of users albums with the Picasa Web API then gets the items in each album so I can filter out unwanted media and directories. It appears to be working as intended, but I am a little concerned that there are some unintended side effects lurking. I would also appreciate advice on how it may be improved.

// callback = function (albumList, error);
function loadAlbumList(callback) {
  var albumListQuery = '?v2&alt=json';
  var request = picasaPath + 'default/'  + albumListQuery;

  authenticatedXhr('GET',request, function (error, httpStatus, responseText) {
    var root = JSON.parse(responseText);
    var feed = root.feed;
    var entries = feed.entry || [], entry;
    var albumList = [], album;
    var ct = 0;

    for (var i = 0; i < entries.length; ++i) {
      (function(index) {
        entry = entries[index];
        loadAlbum(entries[index].gphoto$id.$t, false, function (photos) {
          if(!entries[index].gphoto$albumType && photos.length) {
            album = new Object();
            album.index = index;
            album.name = entries[index].title.$t;
            album.id = entries[index].gphoto$id.$t;
            album.ct = photo.length;
            album.thumb = entries[index].media$group.media$thumbnail[0].url;
            album.checked = false;
            album.photos = photos;
            albumList.push(album);
          }
          if(ct === (entries.length - 1)) {
            albumList.sort(function(a, b) {
              return a.index - b.index;
            });
            callback(albumList, error);
          }
          ct++;
       });
     })(i);
    }
  });
}

// callback = function (albumList, error);
function loadAlbum(id, preload, callback) {
  var request = picasaPath + 'default/albumid/' + id + '/' + photosQuery;

  authenticatedXhr('GET',request, function (error, httpStatus, responseText) {
    var root = JSON.parse(responseText);
    var feed = root.feed;
    var entries = feed.entry || [], entry;
    var imgs = [], img;
    var photos = [],photo;
    var url,author,width,height,aspectRatio;

    for (var i = 0; i < entries.length; i++) {
      entry = entries[i];
      if(isImage(entry)) {
        url = entry.media$group.media$content[0].url;
        width = entry.media$group.media$content[0].width;
        height = entry.media$group.media$content[0].height;
        aspectRatio = width / height;
        author = entry.media$group.media$credit[0].$t;

        if(preload) {
          img = new Image();
       // img.addEventListener('error', _imgError);
          img.src = url;
          imgs.push(img);
        }

        photo = new Object();
        photo.url = url;
        photo.author = author;
        photo.asp = aspectRatio.toPrecision(3);
        photos.push(photo);
      }
    }
    callback(photos, error);
  });
}

// callback = function (error, httpStatus, responseText);
function authenticatedXhr(method, url, callback) {
  var retry = true;
  (function getTokenAndXhr() {
    chrome.identity.getAuthToken({ 'interactive': true },
                                 function (access_token) {
      if (chrome.runtime.lastError) {
        callback(chrome.runtime.lastError);
        return;
      }

      var xhr = new XMLHttpRequest();
      xhr.open(method, url);
      xhr.setRequestHeader('Authorization',
                           'Bearer ' + access_token);
      xhr.send();
      xhr.onload = function () {
        if (this.status === 401 && retry) {
          // This status may indicate that the cached
          // access token was invalid. Retry once with
          // a fresh token.
          retry = false;
          chrome.identity.removeCachedAuthToken(
              { 'token': access_token },
              getTokenAndXhr);
          return;
        }

        callback(null, this.status, this.responseText);
      }
    });
  })();
}


texts:
In this, we are given an array of numbers, say 1 2 3 4.

We start from a given position, let's say the 1st position.
We cancel that number and move forward that many non-cancelled numbers. The number on which we stop again has the same procedure.This is repeated until only one number is left. That is the lucky number.

1 2 3 4

2 3 4

3 4

3

My code:

import java.util.*;

class ln
{
    public static void main(String[] ar)throws Exception
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("How many nos. will you enter: ");
        int n = sc.nextInt();
        int[] a = new int[n];
        System.out.print("Enter the nos.: ");
        for(int i = 0; i < a.length; i++)
            a[i] = sc.nextInt();
        System.out.print("From which position do you want to start: ");
        int st = sc.nextInt();
        for(int i = 0; i < a.length - 1; i++)
        {
            int j = a[st - 1];
            a[st - 1] = 0;
            int s = (int)Math.signum(j);
            while(j != 0)
            {
                if(a[st-1] != 0)
                    j -= s;
                st += s;
                if(st > a.length)
                    st = 1;
                else if(st < 1)
                    st = a.length;
            }
        }
        for(int i = 0; i < a.length; i++)
        {
            if(a[i] != 0)
            {
                System.out.println("Final no.: " + a[i]);
                break;
            }
        }

    }
}

Please tell if there is a more elegant way of doing this .


texts: Determining optimal weight lifting bar configuration

texts:
This program is meant to take two weights and return the best way to load a barbell for two people using different weights, so you don't have to keep changing out super heavy weights. I also made functionality for one person to use it to calculate the most efficient way to load the bar (least # of plates used).

If you notice, user_one() and user_two() are mostly the same code, with minor adjustments. perfect_combo() also shares some of the same.  I feel like there's a way to cut down on the code in this program.

weights=[100, 45, 35, 25, 10, 5, 2.5]
bar_weight = 45
prog_select = int(input('How many people on this bar?'
'(enter 1 or 2) '))
if prog_select == 1:
    target_weight = int(input('Enter weight: '))
elif prog_select == 2:
    target_weight = int(input('Enter first weight: '))
    target_weight1 = int(input('Enter second weight: '))

def user_one():
    nweights = []
    remaining = target_weight - bar_weight
    for  i, weight in enumerate(weights):
        if int(remaining / weight) % 2 == 0:
            nweights.append(int(remaining/ weight))
        else:
            nweights.append(int(remaining/ weight) - 1)
        remaining = remaining - nweights[i]*weights[i]
        if remaining == 0:
            break

    listweights=zip(nweights, weights)
    print(f'{bar_weight}lb bar')
    print(f'{target_weight}lbs')

    for weight in listweights:
        if weight[0] >= 2:
            print(f"{weight[0]} | {weight[1]}'s")

    if remaining !=0:
        print(f'the correct weight combination cannot be found,'
              f'the remaining weight is: {remaining} pound')

def user_two():
    nweights = []
    remaining = target_weight1 - bar_weight
    for  i, weight in enumerate(weights):
        if int(remaining / weight) % 2 == 0:
            nweights.append(int(remaining/ weight))
        else:
            nweights.append(int(remaining/ weight) - 1)
        remaining = remaining - nweights[i]*weights[i]
        if remaining == 0:
            break

    listweights=zip(nweights, weights)
    if prog_select == 1:
        print(f'{target_weight1}lbs')
    else:
        print(f'{bar_weight}lb bar')
        print(f'{target_weight1}lbs')
    for weight in listweights:
        if weight[0] >= 2:
            print(f"{weight[0]} | {weight[1]}'s")

    if remaining !=0:
        print(f'the correct weight combination cannot be found,'
              f'the remaining weight is: {remaining} pound')

def perfect_combo():
    nweights = []
    remaining = (target_weight - target_weight1)

    print("Add " + str(remaining) + "lbs for first weight")

    for  i, weight in enumerate(weights):
        if int(remaining / weight) % 2 == 0:
            nweights.append(int(remaining/ weight))
        else:
            nweights.append(int(remaining/ weight) - 1)
        remaining = remaining - nweights[i]*weights[i]
        if remaining == 0:
            break

    listweights=zip(nweights, weights)

    for weight in listweights:
        if weight[0] >= 2:
            print(f"{weight[0]} | {weight[1]}'s")
    if remaining !=0:
        print(f'the correct weight combination cannot be found,'
              f'the remaining weight is: {remaining} pound')

# Run the program

if prog_select == 1:
    user_one()
elif prog_select == 2:
    remaining = (target_weight - target_weight1)
    if remaining > 99:
        print("You might want to use seperate bars...")
    else:
        user_two()
        perfect_combo()
else:
    print("That's too many peeps on one bar!")


texts: Ruby on rails complex select statement...there has to be a better way!

texts:
I am building a query that could end up look like this:

SELECT "patients".* FROM "patients"
INNER JOIN "users" ON "users"."id" = "patients"."user_id"
WHERE (users.username LIKE '%Bob%' AND users.last_name LIKE '%Smith%'
AND users.active = '1' AND users.disabled = '1')
ORDER BY users.first_name DESC LIMIT 10 OFFSET 0

Below is code to create a complex query such as:

conditions = []
where = ''
where_parameters = []
order = 'users.last_name ASC'
per_page = 20

if is_admin?
  if defined?(params[:username]) and !params[:username].blank?
    where += 'users.username LIKE ? AND '
    where_parameters.push("%#{params[:username]}%")
  end

  if defined?(params[:last_name]) and !params[:last_name].blank?
    where += 'users.last_name LIKE ? AND '
    where_parameters.push("%#{params[:last_name]}%")
  end

  if defined?(params[:active]) and !params[:active].blank?
    where += 'users.active = ? AND '
    where_parameters.push(params[:active])
  end

  if defined?(params[:disabled]) and !params[:disabled].blank?
    where += 'users.disabled = ? AND '
    where_parameters.push(params[:disabled])
  end

  if !where.empty?
    where = where[0, where.length - 5]
    conditions = [where, *where_parameters]
  end

  if defined?(params[:order_by]) and !params[:order_by].blank?
    order = params[:order_by] + ' '
  end

  if defined?(params[:order]) and !params[:order].blank?
    order += params[:order]
  end

  if defined?(params[:per_page]) and !params[:per_page].blank?
    per_page = params[:per_page].to_i
  end
  @patients = Patient.joins(:user).paginate(:all, :include =>:user, :conditions => conditions, :order => order, :page => params[:page], :per_page => per_page)

Is there a better way to do this, this is just ugly?


texts: News-reading application using the Observer pattern

texts:
I have found this question online from an Amazon interview:

  Design a kind of Kindle Fire application where we can subscribe to a news
  channel and read the news from all publishers as a digital format.

I thought that using the Observer design pattern would be a good solution here.

Here is my implementation:

UnitTest class

[TestClass]
    public class ObserverPatternTest
    {
        [TestMethod]
        public void TestMethod1()
        {
            NewsChannel pub1 = new NewsChannel();
            NewsChannel pub2 = new NewsChannel();

            KindleApplication app = new KindleApplication();
            pub1.Subscribe(app);
            pub2.Subscribe(app);
            string tempStory = "story start";

            pub1.NewStory= tempStory;
            Assert.AreEqual(tempStory, app.Message);
            tempStory = " story b";
            pub1.NewStory = tempStory;
            Assert.AreEqual(tempStory, app.Message);
            tempStory = "story pub2";
            pub2.NewStory = tempStory;
            Assert.AreEqual(tempStory, app.Message);
        }
    }

KindleApplication class (Observer)

  public class KindleApplication : ObserverBase
    {
        public string Message { get; set; }
        public override void Update(string message)
        {
            Message = message;
        }
    }

   public abstract class ObserverBase
    {
       public abstract void Update(string message);
    }

NewsChannel class

 public class NewsChannel : publisher
    {
        private string _newStory;

        // Gets or sets subject state
        public string NewStory
        {
            get { return _newStory; }
            set {
                _newStory = value;
                Notify(_newStory);
            }
        }
    }

Publisher class

 public abstract class publisher
    {
        private List<ObserverBase> _observerList;

        public publisher()
        {
            _observerList = new List<ObserverBase>();
        }
        public void Subscribe(ObserverBase app)
        {
            _observerList.Add(app);
        }
        public void Unsubscribe(ObserverBase app)
        {
            _observerList.Remove(app);
        }
        public void Notify(string message)
        {
            foreach (var obesever in _observerList)
            {
                obesever.Update(message);
            }
        }
    }


texts: Leetcode #826. Most Profit Assigning Work solution in Java (Sort + Binary Search)

texts:
Problem Statement:

  We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.

  Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].

  Every worker can be assigned at most one job, but one job can be completed multiple times.

  For example, if 3 people attempt the same job that pays $1, then the total profit will be $3.  If a worker cannot complete any job, his profit is $0.

  What is the most profit we can make?

  Example 1:

  Input:

  difficulty = [2,4,6,8,10]
  profit = [10,20,30,40,50]
  worker = [4,5,6,7]

  Output:

  100

  Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.

  Notes:

  1 <= difficulty.length = profit.length <= 10000
  1 <= worker.length <= 10000
  difficulty[i], profit[i], worker[i]  are in range [1, 10^5]

Solution:

Time Complexity: O(n log n + w log n).
Space Complexity: O(n).

class Solution {
    private static class Job implements Comparable<Job> {
        private int difficulty;
        private int profit;

        public Job(int difficulty, int profit) {
            this.difficulty = difficulty;
            this.profit = profit;
        }

        public int getDifficulty() {
            return difficulty;
        }

        public int getProfit() {
            return profit;
        }

        //Jobs are ordered based on their difficulties
        @Override
        public int compareTo(Job otherJob) {
            int difference = this.getDifficulty() - otherJob.getDifficulty();

            //If both the jobs have the same difficulty, we want the more profitable job to be ordered first so that we get correct maxProfits
            difference = (difference == 0) ? (otherJob.getProfit() - this.getProfit()) : difference;

            return difference;
        }
    }

    private void updateDifficultyAndMaxProfits(Job[] jobs, int[] difficulties, int[] maxProfits) {
        for (int i = 0; i < jobs.length; i++) {
            Job job = jobs[i];
            difficulties[i] = job.getDifficulty();
            if (i == 0) {
                maxProfits[i] = job.getProfit();
            } else {
                maxProfits[i] = Math.max(job.getProfit(), maxProfits[i - 1]);
            }
        }
    }

    public int maxProfitAssignment(int[] difficulties, int[] profits, int[] workers) {
        Job[] jobs = new Job[difficulties.length];

        for (int i = 0; i < difficulties.length; i++) {
            jobs[i] = new Job(difficulties[i], profits[i]);
        }

        Arrays.sort(jobs);

        int[] maxProfits = new int[difficulties.length];
        updateDifficultyAndMaxProfits(jobs, difficulties, maxProfits);

        int totalMaxProfit = 0;

        for (int worker : workers) {
            int workerMaxProfitIndex = Arrays.binarySearch(difficulties, worker);

            //If there isn't an exact match we need to retrieve the index from the insertion point
            if (workerMaxProfitIndex < 0) {
                workerMaxProfitIndex = -(workerMaxProfitIndex + 2);
            }

            //Update totalMaxProfit only if there's at least one task that the worker can accomplish
            if(workerMaxProfitIndex >= 0){
                totalMaxProfit += maxProfits[workerMaxProfitIndex];
            }
        }

        return totalMaxProfit;
    }
}

Please review my code and let me know if there's room for improvement.


texts: Replicating the norwegian flag using CSS

texts:
so here I am trying to get some reviews from my code, where I have to replicate the norwegian flag using flexbox.
First to be sayed is that my teachers told me to divide the flag in two sections, where I have had to insert two of the four squares in eachone, but I ignored this since with declarations like align-content: space-between; I could send the four squares right to the corners and play with margins to adjust them, that's why I just created 4 containers (white squares) with its respective item (red squares).
Before I show my code, I want to tell that it was so diffuicult to me to deal with the size of the elements, first a try to use flex-basis: ; and flex-grow: ; to automatically give size to the squares, but this does'nt work for me, so I have to use width: ; and height: ;.
Due to all this I want to get reccomendations to improve my code or best alternatives to reach the objective and then a kind of explanation about the size of elements.
Here's the code:

body{
    background-color: #00205B;
    margin: 0;
    display: flex;
    flex-wrap: wrap;
    align-content: space-between;
}
.white-square1, .white-square2, .white-square3, .white-square4{
    background-color: #ffffff;
    display: flex;
    align-content: flex-start;
    justify-content: space-between;
    align-items: flex-start;
}
.white-square1, .white-square3{
    margin: 0 50px 50px 0;
    height: 43.8vh;
    width: 25vw;
    flex-grow: 1;
}
.white-square2, .white-square4{
    margin: 0 0 50px 50px;
    height: 43.8vh;
    width: 50vw;
    flex-grow: 2;
}
.white-square3{
    margin: 50px 50px 0 0;
    align-items: flex-end;
}
.white-square4{
    margin: 50px 0 0 50px;
    align-items: flex-end;
}
.red-square1, .red-square2, .red-square3, .red-square4{
    background-color: #BA0C2F;
}
.red-square1, .red-square3{
    margin: 0 50px 50px 0;
    height: 37.8vh;
    width: 25vw;
    flex-grow: 1;
    margin-left: 0;
}
.red-square2, .red-square4{
    margin: 0 0 50px 50px;
    height: 37.8vh;
    width: 50vw;
    flex-grow: 2;
    margin-right: 0;
}
.red-square3{
    margin: 50px 50px 0 0;
    align-items: flex-end;
}
.red-square4{
    margin: 50px 0 0 50px;
    align-items: flex-end;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Flexbox Actividad 3</title>


texts:
I have a deck of flashcards that I want to shuffle.  Here's the method I'm using to shuffle them:

func (deck *Deck) Shuffle() {
        rand.Seed(time.Now().UnixNano())
        randomIndexes := rand.Perm(len(deck.Cards))

        shuffledCards := make([]Card, len(deck.Cards))
        for i := 0; i < len(deck.Cards); i++ {
                shuffledCards[i] = deck.Cards[randomIndexes[i]]
        }

        deck.Cards = shuffledCards
}

Is this an efficient way of doing it, or is there a better way?


texts: Convert an array of doubles to a concatenated Hex string

texts:
I'm working on a tool that converts data between two systems. System 1 presents me with arrays of latitudes and longitudes as doubles. System 2 requires an input of that array as a single Hex string.

I've been calling the following method to do the conversion, and then appending a string with the results, however I'm finding that it is extremely slow, as it's being called 12-13 million times in a typical conversion.

var string = "";
foreach(var value in list<geo>)
string += (DoubleToHex(value.lat) + DoubleToHex(value.lon))

public static string DoubleToHex(double input)
{
    byte[] byteArray = BitConverter.GetBytes(input);
    StringBuilder hex = new StringBuilder(byteArray.Length * 2);
    foreach (byte b in byteArray)
        hex.AppendFormat("{0:x2}", b);
    return hex.ToString().ToUpper();
}

What alternatives exist that would be quicker then using StringBuilder, (or what else am I missing)?


texts: Edit button toggles modal and load data from PHP using AJAX and JQUERY

texts:
I've been working on an edit/update button that will toggle a modal that looks like this:

Is there a better code for this JavaScript code that I made?

<script>

$('body').on('click', '.editButton',function(){
    let edit = $(this).val()
    console.log("Edit this : " + edit);

    $('#updateEmpModal').modal('toggle');

    $.ajax({
        type    :   'POST',
        url     :   'get.php',
        data    :   {'edit' : edit},
        dataType:   'json',
        success: function(data){
            $("#updateEmpForm input[name='EMAIL']")         .val(data.EMAIL);
            $("#updateEmpForm input[name='PASSWORD']")      .val(data.PASSWORD);
            $("#updateEmpForm input[name='RIGHTS']")        .val(data.RIGHTS);
            $("#updateEmpForm input[name='LAST_NAME']")     .val(data.LAST_NAME);
            $("#updateEmpForm input[name='FIRST_NAME']")    .val(data.FIRST_NAME);
            $("#updateEmpForm input[name='MIDDLE_NAME']")   .val(data.MIDDLE_NAME);
            $("#updateEmpForm input[name='SUFFIX']")        .val(data.SUFFIX);
            $("#updateEmpForm input[name='GENDER']")        .val(data.GENDER);
            $("#updateEmpForm input[name='BIRTHDATE']")     .val(data.BIRTHDATE);
            $("#updateEmpForm input[name='BIRTHPLACE']")    .val(data.BIRTHPLACE);
            $("#updateEmpForm input[name='CITIZENSHIP']")   .val(data.CITIZENSHIP);
            $("#updateEmpForm input[name='RELIGION']")      .val(data.RELIGION);
            $("#updateEmpForm input[name='ADDRESS']")       .val(data.ADDRESS);
            $("#updateEmpForm input[name='CONTACT']")       .val(data.CONTACT);
            $("#updateEmpForm input[name='ICE_NAME']")      .val(data.ICE_NAME);
            $("#updateEmpForm input[name='ICE_CONTACT']")   .val(data.ICE_CONTACT);
            $("#updateEmpForm input[name='DEPARTMENT']")    .val(data.DEPARTMENT);
            $("#updateEmpForm input[name='POSITION']")      .val(data.POSITION);
            $("#updateEmpForm input[name='EMP_TYPE']")      .val(data.EMP_TYPE);
            $("#updateEmpForm input[name='edit']")          .val(data.ID);
        }
    });
});

</script>

It is working, but I want to know if this is a bad practice and if there are better solutions.


texts: Calculating the surrounding objects in a two-dimensional coordinate system leaving out the corners

texts:
We have a dynamically created map with two dimensional coordinates. There's an object in this map on a random position and I need to validate the four adjacent fields. However, I need to leave out the corners since they are not relevant for the validation!

This is an illustration of what needs to be validated (the green fields saying "v"):

  Instance-Example: Object ("O") is on (2;2)
  Line above the object: Y-Coordinate is 1 (so, 2 - 1 )
  Line above the object: Needed x-coordinate is 2 (so, 2 + 0 )
  Line of the object: Y-Coordinate is 2 (so, 2 + 0 )
  Line of the object: Needed x-coordinate is 1 (so, 2 - 1 )
  Line of the object: Needed x-coordinate is 3 (so, 2 + 1 )
  Line beneath the object: Y-Coordinate is 3 (so, 2 + 1 )
  Line beneath the object: Needed x-coordinate is 2 (so, 2 + 0 )

Here is my solution.  The core magic lays within the inner for loop.

public bool validateEdibility ()
{

    for (int line = -1; line < 2; line ++)
    {

        for (int column = Math.Abs(line) - 1; column < 2; column += 2)
        {

                if (!(this.MyWorld.getObjectOnPosition(this.Y + line, this.X + column) is Wall))
                {

                    return true;

                }

        }

    }

    return false;

}

The first idea behind this code is to get an integer which represents the subtrahend for the specific coordinate of the object. For example we need to have "-1" for the y-coordinate if we want to iterate through the first line (the line above the object).

With this idea we need to get a sequence like this:

Line: -1

Column: 0

Line: 0

Column: -1
Column: 1

Line: 1

Column: 0

The second idea is the horizontal for loop (the inner loop). We take the absolute of the line and subtract it with 1. This provides us the right first and last sequence since we've terminated the only difference between them: the negative sign.

Than we add +2 to the index for each run since the only line surviving this is the one in the middle ("0"). Remember: we subtract 1, so the 0-line starts with "-1".

I think this is quite a brainfuck and that's why I wonder if there's a more elegant way to solve this. Is the code evolving from these ideas somehow improvable?


texts:
Scenario : Sending a POST to 2 different endpoints (not related to or dependent on each other).

I'm really just not sure if I went about this correctly, and whether or not the responses will have returned from the context before the method returns. I have read some about async/await and the context for which it operates, etc., but I'm still not sure.

class Program
    {
        static void Main(string[] args)
        {
            Task.Run(async () =>
            {
                await SendRequests(cookie, request1, request2);
            })
            .GetAwaiter()
            .GetResult();

        }

static async Task<List<HttpResponseMessage>> SendRequests(Cookie cookie, HttpRequestMessage punchRequest, HttpRequestMessage request2)
        {
            List<HttpResponseMessage> responseMessages = new List<HttpResponseMessage>();

            CookieContainer cookies = new CookieContainer();
            HttpClientHandler handler = new HttpClientHandler();
            handler.CookieContainer = cookies;
            cookies.Add(cookie);

            using (var httpClient = new HttpClient(handler))
            {
                var response1 = await httpClient.SendAsync(request1);
                var response2 = await httpClient.SendAsync(request2);

                responseMessages.AddRange(new [] { response1 , response2 });

                return responseMessages;
            }
        }

    }

I'm wondering if :

Task.Run( async () => ....) is correct here, as well as GetAwaiter/GetResult
Can the SendRequests method ever return before the requests finish / get resolved?


texts:
I wrote a function for repeating a string to a certain length.

For example:

ExpandString("Test", 11);

// output: "TestTestTes"

Are there any optimizations or fixes that can be done to this function?

private string ExpandString(string str, int length)
{
    if (length <= str.Length) return str.Substring(0, length);
    var result = str;
    for (var i = str.Length; i < length; i++)
    {
        result += str[i % str.Length];
    }
    return result;
}


texts: Counting the positive integer solutions of an equation

texts:
I have to solve this equation: \$ x + y + xy = n \$

#include <iostream>
#include <cstring>

using namespace std;

long c;

int main()
{
   long x = 0;
   cin >> c;
   if(c == 0)
   {
       cout << 1 << endl;
       return 0;
   }
   for(long i = 1; i <= c / 2; i ++)
   {
       for(long j = 1; j <= c; j ++)
           if(i + j + i * j == c)
           {
                       x ++;
                   break;
           }
   }
   cout << x + 2 << endl;
}

Of course this code is very slow. How can I find a positive number of solutions in a faster way? Maybe there is a specific algorithm?


texts: Longest sequence of same subsequent number in a square matrix

texts:
Given an N-by-N grid with each cell either occupied by an 'X', an 'O', or empty, write a program to find the longest sequence of consecutive 'X's either horizontal, vertically, or diagonally. To test your program, you can create a random grid where each cell contains an 'X' or 'O' with probability 1/3.

I would like a review of my answer. I'm not sure it's efficient enough, or even efficient at all. I chose to use numbers for now since they easier to work with. I hope it's all clear.

class Main {
    public static void main(String[] args){
        int n = 4;
        int[][] grid = new int[n][n];
        int max =  Integer.MIN_VALUE;

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

                // three nums are produced. there is 1/3 chance for each.
                int r = (int)(Math.random()*3);

                // both 'X' and 'O' have 1/3 chance to be produced.
                if(r == 1) grid[i][j] = 1;
                if(r == 2) grid[i][j] = 2;

                System.out.print(grid[i][j]+" ");
            }
            System.out.println();
        }

        // horizontal, vertical, backward diag, forward diag
        int hori  = 0, vert = 0, bdia = 0, fdia = 0;

        // assuming 1 represents 'X' and 2 represents 'O'
        int num   = (int)(1 + Math.random()*2);

        for(int i = 0; i < n; i++){
            hori = 0; vert = 0;
            // horizontal instances
            for(int j = 0; j < n; j++){
                if(grid[i][j] != num)
                    hori = 0;
                else hori ++;
                max = hori > max? hori: max;
            }

            // vertical  instances
            for(int j = 0; j < n; j++){
                if(grid[j][i] != num)
                    vert = 0;
                else vert ++;
                max = vert > max? vert: max;
            }

            // forward diag instances (fdia)
            for(int j = 0; j < n && i == 0; j++){
                if(grid[j][j] != num)
                    fdia = 0;
                else fdia ++;
                max = fdia > max? fdia: max;
            }

            // backward diag instances (bdia)
            for(int j = 0; j < n && i == 0; j++){
                if(grid[j][n-1-j] != num)
                    bdia = 0;
                else bdia ++;
                max = bdia > max? bdia: max;
            }
        }

        System.out.println("max : "+max);
        System.out.println("num : "+num);
    }
}


texts:
Is this the right way to do a singleton in Objective-C (coming from an Android background, with a little understanding of threading)?

#import "ItemsManager.h"

#define kNumMaxSelectableItems 15

@implementation ItemsManager{
    NSMutableArray *currentItems;
}

static ItemsManager *myself;

-(id)init{
    if(self=[super init]){
        currentItems = [[NSMutableArray alloc] initWithCapacity:kNumMaxSelectableItems];
        myself = self;
    }
    return self;
}

+(ItemsManager *)getInstance{
    if(!myself){
        myself = [[ItemsManager alloc] init];
    }
    return myself;
}

-(void) doSomething{
    NSLog(@"hi");
}

-(void)dealloc{
    [currentItems release];
    currentItems = nil;
    myself = nil;

    [super dealloc];
}

@end

And with this design, I suppose I would call it like:

void main(){
    [[ItemsManager getInstance] doSomething];
}


texts: Singleton method for Redis connection in Python

texts:
Here's my class for providing a singleton instance of a Redis connection. What do you think?

from redis import StrictRedis
import os

class RedisConnection(object):
    REDIS_URL = os.environ['REDIS_URL']

    def __init__(self):
        self._redis = StrictRedis.from_url(self.REDIS_URL)

    def redis(self):
        return self._redis

    the_instance = None
    @classmethod
    def singleton(cls):
        if cls.the_instance == None:
            print "assigning!"
            cls.the_instance = cls().redis()
        return cls.the_instance


texts: Bash - script to encrypt pdf files using pdfencrypt

texts:
I wrote a small script to get around the issue when using pdfencrypt on the command line the password is always echoed as well as being saved to the 'history'.

#!/bin/bash

 export LC_ALL=de_DE.latin1

 while true; do
     echo "please select Pdf input file:"
     read -e -r infile
     if file --mime-type "$infile" | grep -q pdf$; then
         echo
         break
     else
         printf "\nis not a PDF file :-(\n\n"
     fi
 done

 echo "please type in Pdf output filename"
 echo "without extension (.pdf):"
 read -e -r outfile

 if [ -f "${outfile}.pdf" ]; then
     echo
     echo "File allready exists!";
     echo "please enter a new filename, or the same to override: "
     read -e -r outfile
 fi

 echo "please type in Password"
 echo "(only ASCII chracters recommended)"
 read -r -s

 pdfencrypt "$infile" -p "$READ" -o "${outfile}.pdf" \
  && echo "success, ${outfile}.pdf is encrypted :-)" \
  || echo "failed, did you use non ASCII characters for Password?"

exit

I had the problem with following non ASCII-Characters in the password:
§ ä ö ü etc. When I used any of those for encryption I got the following error:

  Encoding::CompatibilityError: incompatible character encodings: UTF-8 and ASCII-8BIT

I solved this by including export LC_ALL=de_DE.latin1 in the script. Though there still are some compatibility problems when using any of those characters, therefore I added a recommendation not to use non ASCII in the password.

(I know that PDF encryption itself is pretty low-level security but I sometimes like to add this level when sending files via e-mail etc...)


texts:
I have this script that pulls text out of .docx, .doc and .pdf files and uploads that text to an Azure SQL Server. This is so users can search on the contents of those documents without using Windows Search / Azure Search.

The filenames are all in the following format:

firstname surname - id.extension

The id is incorrect though, the ID is from an outdated database and the new database that I am updating holds both (newID and oldID).

COLUMNS:

ID - New ID of the candidate record
OldID - Old ID of the candidate record (old database schema)
OriginalResumeID - Document link ID for the candidate table to the document table
CachedText - The field I am updating (holds the document text) at the moment this will mostly be NULL

Here is the script:

## Get resume list
$params = @{
    'Database' = $TRIS5DATABASENAME
    'ServerInstance' = $($AzureServerInstance.FullyQualifiedDomainName)
    'Username' = $AdminLogin
    'Password' = $InsecurePassword
    'query'    = "SELECT id, OldID, OriginalResumeID FROM Candidate WHERE OriginalResumeID IS NOT NULL"
}
$IDCheck = Invoke-Sqlcmd @params

## Word object
$files = Get-ChildItem -force -recurse $documentFolder -include *.doc, *.pdf, *.docx
$word = New-Object -ComObject word.application
$word.Visible = $false
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatText")

foreach ($file in $files) {
    Write-Output "Processing: $($file.FullName)"
    $doc = $word.Documents.Open($file.FullName)
    $fileName = $file.BaseName + '.txt'
    $doc.SaveAs("$env:TEMP\$fileName", [ref]$saveFormat)
Write-Output "File saved as $env:TEMP\$fileName"
    $doc.Close()

    $4ID = $fileName.split('-')[1].replace(' ', '').replace(".txt", "")
    $text = Get-Content "$env:TEMP\$fileName"
    $text = $text.replace("'", "''")

    $resumeID = $IDCheck | where {$_.OldID -eq $4id} | Select-Object OriginalResumeID
    $resumeID = $resumeID.OriginalResumeID

    <# Upload to azure #>
    $params = @{
        'Database' = $TRIS5DATABASENAME
        'ServerInstance' = $($AzureServerInstance.FullyQualifiedDomainName)
        'Username' = $AdminLogin
        'Password' = $InsecurePassword
        'query'    = "Update Document SET CachedText = '$text' WHERE id = $ResumeID"
    }
    Invoke-Sqlcmd @params -ErrorAction "SilentlyContinue"
    Remove-Item -Force "$env:TEMP\$fileName"
}

$word.Quit()

The problem is that running this on a large dataset, let's say 750000 documents takes far too long per document. I'm fairly certain that this is because it has to search through the entire $IDCheck object of 750000 records before it can get the originalResumeID of the record to upload to.

Running this on a smaller database is quite quick (around 200000 per 24 hours). I was thinking I could check the documents table and only pull rows where the CachedText field is null and loop that to run every 50000 documents so it would get quicker as it goes. Problem is the documents table will be massive and will take a long time to search through every time this is called.

Any help on speeding this up would be much appreciated.

EDIT:

Looks like it is the upload to azure causing the delay:

<# Upload to azure #>
$params = @{
    'Database' = $TRIS5DATABASENAME
    'ServerInstance' = $($AzureServerInstance.FullyQualifiedDomainName)
    'Username' = $AdminLogin
    'Password' = $InsecurePassword
    'query'    = "Update Document SET CachedText = '$text' WHERE id = $ResumeID"
}
Invoke-Sqlcmd @params -ErrorAction "SilentlyContinue"


texts:
I just wrote this function and I was curious if anyone could find any flaws in it.

It look pretty secure to me but I just want to make sure since I'm no cryptography expert.

function urandom_rand($min, $max) {

    if ($max <= $min) {
        trigger_error('Minimum value must be greater than maximum value.');
    }

    $maxHex = dechex($max);
    $maxHexLength = strlen($maxHex);
    $ivSize = (int)($maxHexLength + ($maxHexLength % 2)) / 2;
    // Reads bytes from /dev/urandom (or its Windows equivalent) - byte size is based on max value
    $r = hexdec(bin2hex(mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM)));
    // Min/max modulo conversion to avoid using floats/round which is imprecise and prone to attacks
    $r = (($r - $min) % ($max - $min + 1) + ($max - $min + 1)) % ($max - $min + 1) + $min;
    return $r;
}


texts:
Is it possible to improve this code in terms of efficiency / line number ? (avoid nested code ...). It comes from a test I failed. I don't know how I could have done it better.

from collections import Counter

def parse_molecule(molecule):

    array = [[]]

    for token in map(str, molecule):
        if token.isalpha() and token.istitle():
            last = [token]
            upper = token
            array[-1].append(token)
        elif token.isalpha():
            last = upper + token
            array[-1] = [last]
        elif token.isdigit():
            array[-1].extend(last*(int(token)-1))
        elif token == '(' or token == '[':
            array.append([])
        elif token == ')' or token == ']':
            last = array.pop()
            array[-1].extend(last)

    return dict(Counter(array[-1]))

Examples of function usage are following:

>>> water = 'H2O'
>>> parse_molecule(water)
>>>{'H': 2, 'O': 1}

>>> magnesium_hydroxide = 'Mg(OH)2'
>>> parse_molecule(magnesium_hydroxide)
>>> {'Mg': 1, 'O': 2, 'H': 2}

>>> fremy_salt = 'K4[ON(SO3)2]2'
>>> parse_molecule(fremy_salt)
>>> {'K': 4, 'O': 14, 'N': 2, 'S': 4}

This is the statement:

  For a given chemical formula represented by a string, count the number
  of atoms of each element contained in the molecule and return a dict.

For example:

water = 'H2O'
parse_molecule(water)
return {'H': 2, 'O': 1}

magnesium_hydroxide = 'Mg(OH)2'

parse_molecule(magnesium_hydroxide)

return {'Mg': 1, 'O': 2, 'H': 2}

fremy_salt = 'K4[ON(SO3)2]2'

parse_molecule(fremy_salt)

return {'K': 4, 'O': 14, 'N': 2, 'S': 4}

As you can see, some formulas have brackets in them. The index outside the brackets tells you that you have to multiply count of each atom inside the bracket on this index. For example, in Fe(NO3)2 you have one iron atom, two nitrogen atoms and six oxygen atoms.

Note that brackets may be round, square or curly and can also be nested. Index after the braces is optional.


texts: Manage list of subjects (show, delete, add) in Python

texts:
This is my code. It loops a menu, from which you can select whether you want to add a subject, see all subjects or delete a subject. Is there anything style- or functionality-wise to add or correct?
def add_subject(subjects):

    # ask for subject to add
    add = input("\nWhat subject do you want to add? ")

    # if subject not already in list, add subject
    subjects.append(add) if not add in subjects else print("\nSubject already in list.")

def show_subjects(subjects):

    # show all subjects
    print("\nThese are your subjects: ", subjects)

def delete_subject(subjects):

    # ask for subject to delete
    delete = input("\nPlease enter subject to delete: ")

    # if subject is in list, delete subject
    subjects.remove(delete) if delete in subjects else print("\nSubject not found.")

def main():

    # initialise list of sample subjects
    subjects = ["Math","Science","English"]

    # loop action cycle
    while 1:
        try:
            # ask user for selection
            selection = int(input("\nPlease enter option: \n(1) Add subject\n(2) Show all subjects\n(3) Delete a subject\n(4) Quit\n"))

            # call associated function
            if selection == 1:
                add_subject(subjects)
            elif selection == 2:
                show_subjects(subjects)
            elif selection == 3:
                delete_subject(subjects)
            elif selection == 4:
                break
            else:
                raise ValueError

        except ValueError:
            print("\nNot a viable option. Please pick 1, 2 or 3.")

if __name__ == "__main__":
    main()


texts:
Was tinkering around in Python after a long hiatus, and decided to do a very simple fake telephone generator.

Anything I can do to improve it?

import random

areacode = input("Enter your desired area code prefix: ")
print(areacode + "-", end='')
for i in range(3):
    print(random.randint(0,9), end='')

print("-",end='')

for j in range(4):
    print(random.randint(0,9), end='')

What are some of the things I should keep in mind syntax wise? I feel like I'm using unnecessary looping here.


texts: 3-layer ASP.NET app - Need critique/advice

texts:
My current setup is a 3 layered application: UI > BLL > DAL. Each layer is set up as a separate project. The UI is an ASP.Net website and the BLL & DAL are Class Library projects.

I've shown some sample code from each of my layers. Hopefully you guys can critique my application design and give me some tips/pointers or I'm doing this wrong, steer me in the right direction. Thanks!

DAL Method:

public static object Get_UserId(string username)
{
    ConnectionSettings connectionSettings = new ConnectionSettings();
    SqlConnection sqlConnection = new SqlConnection(connectionSettings.ConnectionString);
    string sql = String.Format("select UserId from Users where Username = '{0}'", username);
    try
    {
        sqlConnection.Open();
        SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
        return sqlCommand.ExecuteScalar();
    }
    catch
    {
        throw new DALException("Unable to retreive User ID");
    }
    finally
    {
        sqlConnection.Close();
    }
}

The BLL method responsible for retreiving User ID:

 public static int GetUserId(string username)
 {
     try
     {
         int userId = Int32.Parse(UserDAL.Get_UserId(username).ToString());
         return userId;
     }
     catch (Exception ex)
     {
         throw new BLLException(ex.Message);
     }
 }

The call to the BLL from UI:

try
{
    int id = UserBLL.GetUserId("bobloblaw");
    Response.Write(id);
}
catch (DALException dalEx)
{
    Response.Write(dalEx.Message);
}
catch (BLLException bllEx)
{
    Response.Write(bllEx.Message);
}


texts:
I have a table (Oracle):

customer_quote
------
int id
int part_key (fk)
int condition_code (fk)
number unit_price
int qty_quoted
date entry_date

With a query that selects data from the past year:

SELECT cq.part_key
    , cq.condition_code
    , COUNT(*) AS cq_count
    , SUM(cq.unit_price * cq.qty_quoted) AS cq_total
    , SUM(cq.qty_quoted) cq_qty
FROM customer_quote cq
WHERE cq.entry_date > TO_DATE('09-Jun-2017', 'dd-mm-yyyy')
GROUP BY cq.part_key
    , cq.condition_code

But I needed the data to include parts with activity from the past two years but data older than 1 year shouldn't calculate into the totals. So I wrote this query:

SELECT cq.part_key
    , cq.condition_code
    , COUNT(case when cq.entry_date > TO_DATE('09-Jun-2017', 'dd-mm-yyyy') then 1 END) AS cq_count
    , SUM(case when cq.entry_date > TO_DATE('09-Jun-2017', 'dd-mm-yyyy') then (cq.unit_price * cq.qty_quoted) END) AS cq_total
    , SUM(case when cq.entry_date > TO_DATE('09-Jun-2017', 'dd-mm-yyyy') then cq.qty_quoted END) cq_qty
FROM customer_quote cq
WHERE cq.entry_date > TO_DATE('09-Jun-2016', 'dd-mm-yyyy')
GROUP BY cq.part_key
    , cq.condition_code

The where date is 2 years ago but the case when dates are all 1 year ago. This query works, but is it optimal? I think there's probably a way to merge the case when statements into 1.

Performance is my main concern, readability is only marginally important.

Worth noting: the final SQL query will be a parameterized SQL Java object so the date will be a CASE WHEN cq.entry_date > ? THEN and inserted using PreparedStatement::setDate() so with my solution I will need to do setDate() x 4.


texts: Project Euler # 25 The 1000 digit Fibonacci index

texts:
The Fibonacci sequence is defined by the recurrence relation:

  Fn = Fn−1 + Fn−2, where F1
  = 1 and F2 = 1.

  Hence the first 12 terms will be:

  F1 = 1
  F2 = 1
  F3 = 2
  F4 = 3
  F5 = 5
  F6 = 8
  F7 = 13
  F8 = 21
  F9 = 34
  F10 = 55
  F11 = 89
  F12 = 144

  The 12th term, F12, is the first term to contain three digits.

  What is the index of the first term in the Fibonacci sequence to
  contain 1000 digits?

from time import time

def fib(n):
    """returns index of the first fibonacci of length n digits."""
    fibs = [0, 1]
    while len(str(fibs[-1])) < n:
        fibs.append(fibs[-1] + fibs[-2])
    return len(fibs) - 1

if __name__ == '__main__':
    time1 = time()
    print(fib(1000))
    print(f'Time: {time() - time1} seconds.')