texts: Check if bit is only set once in a vector of int

texts:
I have a vector of uint16_t and I want to check if there is a bit which is only set in one vector.  I then get its position within the vector as well as from the bit.

Let's say we have:

v[0] = 0100
v[1] = 0110
v[2] = 1001

I would like to know that ind = 1 and val = 2.

In clumsy code this would be like that:

#include <cstdint>
#include <vector>
#include <fstream>

const uint16_t N = 10;

int main() {
    // Create a dataset
    std::vector<uint16_t> vec(N, (1 << 2) + (1 << 3));
    vec[3] = (1 << 5);
    vec[6] = (1 << 7);

    // loop over the values
    for (auto i = 0; i < 16; i++) {
        uint16_t counter = 0,ind;

        // loop over the vector
        for (auto ii = 0; ii < N; ii++) {
            if (vec[ii] & (1 << i)) {
                if (counter++ == 1) { break; }
                ind = ii;
            }
        } // vector loop

        // Do we only have a single value?
        if (counter == 1) {
            printf("%i @ %i\n",i,ind);
        }
    } // value loop
} // main

Is there a better way to do this?  In case it matters using g++ with Ubuntu.


texts: Using recursion to count nodes in a binary tree, test equality of linked lists, and find extrema of a linked list

texts:
I am working with a some small functions to test recursion. I am fairly new to Python and am wondering if there is a cleaner way to get the job done.

def count(t,p):

    ''' recursive function when passed a binary tree (it doesn’t matter if it is a
    binary search tree) and a predicate as arguments; it returns a count of all the
    values in the tree for which the predicate returns True. '''
    if t == None or t.value == None:
        return 0
    elif p(t.value):
        return 1 + count(t.right, p) + count(t.left, p)
    else:
        return count(t.right, p) + count(t.left, p)

def equal(ll1,ll2):

    ''' recursive function when passed two linked lists; it returns whether or not
    the linked lists contain exactly the same values in the same order. '''
    if ll1 == None and ll2 == None:
        return True
    if (ll1 != None and ll2 == None) or\
        (ll2 != None and ll1 == None):
        return False
    elif ll1.value == ll2.value:
        return equal(ll1.next, ll2.next)
    else:
        return False

def min_max(ll):

    ''' a recursive when passed a linked list; it returns a 2-tuple containing the
    minimum value followed by the maximum value. If the linked list is empty, return
    (None, None) '''
    if ll == None:
        return None, None
    maybe_min, maybe_max  = min_max(ll.next)
    if maybe_min == None or ll.value < maybe_min:
        least = ll.value
    if maybe_min != None and ll.value > maybe_min:
        least = maybe_min
    if maybe_max == None or ll.value >= maybe_max:
        most = ll.value
    if maybe_max != None and ll.value < maybe_max:
        most = maybe_max
    return least, most


texts: A PHP Controller, which feels to 'array-like', in Laravel

texts:
This is a controller, which receives the validated input from a http request, then finds the assorted model and for each translation key in the received data, it will add it to the model.

public function update(UpdateMenuItemRequest $request)
{
    $validated = $request->validated();

    $item = MenuItem::findOrFail($validated['id']);

    foreach($validated['translations'] as $validatedTranslation) {
        $item->translations()->updateOrCreate(['locale' => $validatedTranslation['locale']], $validatedTranslation);
    }

    return $item;
}

Is this Object Oriented enough? It doesn't seem like this method is violating SRP in the first place, or could it be improved? Thank you.


texts: Locating contact information from a CSV spreadsheet

texts:
I'm trying to find a more effective way to access variables within for loops. I felt that my attempt which works is not an effective way to access variables that are within for loops.

mylist=None is the variable in which I want to access within the for loop.

Also, I want to find a way to minimize the lines of my code either using functions or other suggested approaches and etc.

import csv
import os
from var_dump import var_dump
from orderedset import OrderedSet

# if phone or websites dont appear on spreadsheet change the row indexs

fil = 'newfiles/output8.csv'
with open(fil) as csvfile:
    readCSV = csv.reader(csvfile, delimiter=",")
    websites = OrderedSet()
    phonenumbers = OrderedSet()
    emails = OrderedSet()
    locations = list()
    mylist = None
    data = ["electric", "electricians"]
    # remove urls that have these strings,  only works with the first string
    # but not second one.
    remo = ["listings", "nationwide", "/mip", "car", "/locations", "/YB", "?utm_source", "/locallocksmithnearby",
            "key.me", "find-locksmiths-near-me", "premium-locksmiths", "locksmithnearyou24hrs"]
    for row in readCSV:
        website = row[1].strip('[]\'')
        email = row[0].lower().strip('[]\'')
        phonenumber = row[2]
        location = row[3]
        if location:
            if website not in websites:
                if phonenumber not in phonenumbers:
                    if email not in emails:
                        for x in data:
                            if x in website:
                                for r in remo:
                                    if all(r not in website for r in remo):
                                        if phonenumber not in phonenumbers:
                                            if email not in emails:
                                                websites.add(website)
                                                phonenumbers.add(phonenumber)
                                                emails.add(email)
                                                locations.append(location)
                                                mylist = zip(emails, websites, phonenumbers, locations)

    if mylist is not None:
        number = 0
        while os.path.exists('newfiles/newoutput%s.csv' % number):
            number += 1
        with open('newfiles/newoutput%s.csv' % number, 'w') as csvfile:
            writer = csv.writer(
                csvfile, delimiter=",")
            writer.writerow(
                ['Email', 'Website', 'Phone Number', 'Location'])
            # var_dump(mylist)
            for i in mylist:
                writer.writerow(list(i))


texts:
So this original piece of code:

const imgUrls = {};

function onXhrLoad() {
  const json = JSON.parse(this.response);
  const photos = json.photos ? json.photos.photo : [json.photo];
  for (const {id, url_o} of photos) {
    imgUrls[id] = url_o;
  }
}

The original code assumed that the biggest available url to an image in the object "photos" is "url_o", but sometimes that size is not available so I wanted to change the "url_o" in the last 2 lines to the biggest size available in "photos" using the array size (array "size" in the modified code is the order of sizes from biggest to smallest).

so I modified the code as follows:

const imgUrls = {};
const sizes = ['url_o', 'url_6k', 'url_5k', 'url_4k', 'url_3k', 'url_k', 'url_h', 'url_l'];

function onXhrLoad() {
  const json = JSON.parse(this.response);
  const photos = json.photos ? json.photos.photo : [json.photo];
  for (var p of photos) {
    for (var s of sizes) {
        if (s in p) {
            var url = p[s];
            break;
        }
    }
    const id = p.id;
    imgUrls[id] = url;
  }
}

As requested in a comment, there is an example response at this link.
In this response there is no url_o, the biggest is url_6k

My question is if there is a better way to change the "url_o" than going through two for loops and an if condition.


texts: Implement jquery like functions addClass, removeClass and delay in Javascript

texts:
Assume $ is not the browser. Now have to implement $, it will take a string, which is a query, it will use the querySelector to select the element. (Reference: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector)

$('text')

Now implement jquery like functions addClass and removeClass. (Reference: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList)

$('#test').removeClass('blue').addClass('red');

Now implement jquery like functions delay. (Reference: https://api.jquery.com/delay/)

$('#test').removeClass('blue').delay(2000).delay(1000).addClass('red');

Code Sample

function $(selector) {
    let element = document.querySelector(selector)
    element.queue = []
    element.active = false
    return element
}

Element.prototype.next = function () {
    if (this.queue.length) this.runTask(this.queue.shift())
}

Element.prototype.runTask = function (callBack) {
    this.active = true
    callBack().then(() => {
        this.active = false
        this.next()
    })
}

Element.prototype.register = function(callBack){
    if (this.active) {
        this.queue.push(callBack)
    } else {
        this.runTask(callBack)
    }
}

Element.prototype.addClass = function (className) {
    that = this
    let callBack = () => new Promise(resolve => setTimeout(function () {
        that.classList.add(className)
        resolve()
    }, 0))
    this.register(callBack)
    return this
}

Element.prototype.removeClass = function (className) {
    that = this
    let callBack = () => new Promise(resolve => setTimeout(function () {
        that.classList.remove(className)
        resolve()
    }, 0))
    this.register(callBack)
    return this
}

Element.prototype.delay = function (ms) {
    that = this
    let callBack = () => new Promise(resolve => setTimeout(function () {
        resolve()
    }, ms))

    this.register(callBack)
    return this
}

$('#test')
.removeClass("red").delay(500)
.addClass("blue").delay(500).delay(500).removeClass("blue")
.delay(500).addClass("red").delay(500).removeClass("red")
.delay(500).addClass("blue").delay(500).removeClass("blue")
.delay(500).addClass("red").delay(500).removeClass("red")
<!DOCTYPE html>

Can anyone please review the Code?


texts: Horridly Inefficient Project Euler #14 in Python - Collatz Sequences

texts:
I created this solution a while ago, and have been going back over my problems to try to make them all more efficient. I have been stuck on this one, and have tried a few different ideas. So far, my original code has still been the "quickest" at over 2 minutes.

Here is the problem and original solution I came up with:

  The following iterative sequence is defined for the set of positive integers:

  n → n/2 (n is even) n → 3n + 1 (n is odd)

  Using the rule above and starting with 13, we generate the following
  sequence:

  13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this
  sequence (starting at 13 and finishing at 1) contains 10 terms.
  Although it has not been proved yet (Collatz Problem), it is thought
  that all starting numbers finish at 1.

  Which starting number, under one million, produces the longest chain?

  NOTE: Once the chain starts the terms are allowed to go above one
  million.

MAX_LENGTH = 0
NUM = 0
SEQ = []

def nextTerm(num):
    if num != 1:
        if num % 2 == 0:
            return num / 2
        else:
            return (3 * num) + 1
    if num == 1:
        return 1

current = 2
SEQ.append(current)

for num in range(1000001):
    while current >= 1:
        if current > 1:
            current = nextTerm(current)
            SEQ.append(current)
        if current == 1:
            SEQ.append(current)
            break

    if len(SEQ) > MAX_LENGTH:
        MAX_LENGTH = len(SEQ)
        NUM = num

    current = num + 1
    SEQ = []

print("The number {} produced the max sequence length of {}.".format(NUM,
                                                                     MAX_LENGTH
                                                                     ))

# The number 837799 produced the max sequence length of 525.
# Time: 143.42219 seconds

The thing with this is, I know that for many, many numbers, it will end up creating another seq with the last 95% of the sequence being the same, if that makes sense. So I tried creating a way to check if it will end up being the same as another sequence created, and if so, instead of calculating the rest of the sequence, just copy the other one that's the same. This obviously uses a lot more memory as I'm holding a list of lists now instead of a single list, but I thought the time would still be shorter. After waiting 5 minutes while it was running, I just gave up. I still think this might be a good way to think about and approach the problem, so here is the code for that thought process:

def next_term(num):
    if num != 1:
        if num % 2 == 0:
            return num / 2
        else:
            return (3 * num) + 1
    if num == 1:
        return 1

current = 2
MAIN_SEQ = []
seq = []
MAX_LENGTH = 0
NUM = 0

for num in range(1000001):
    seq = [2]
    while current >= 1:
        for lst in MAIN_SEQ:
            if current in lst:
                seq.append(item for item in lst[lst.index(current):])
                break
        if current > 1:
            seq.append(current)
            current = next_term(current)
        if current == 1:
            seq.append(1)
            MAIN_SEQ.append(seq)
            break

    if len(seq) > MAX_LENGTH:
        MAX_LENGTH = len(seq)
        NUM = num

    current = num + 1

print("The number {} produced the max sequence length of {}.".format(NUM,
                                                                     MAX_LENGTH
                                                                     ))

I would still consider myself a beginner in Python, so clear explanations for what I'm doing inefficiently are very welcome.


texts: Using an offset variable to keep track of the next item in a Rust array

texts:
I am using an offset variable to track the iteration position, and modifying / returning it. Is the below considered bad practice in Rust? I ask this because I don't see dereferencing very often in code I have seen.

fn get_next_u16(input: &[u8], offset: &mut usize) -> u16 {
    let next = ((input[*offset+1] as u16) << 8) +
                (input[*offset]   as u16);
    *offset += 2;
    next
}

fn main() {
    let input = [1, 2, 3, 4];
    let mut offset = 0;
    let first_u16 = get_next_u16(&input, &mut offset);
    let second_u16 = get_next_u16(&input, &mut offset);
    println!("first: {}", first_u16);
    println!("second: {}", second_u16);
}

The other way I think of doing this is to reassign to the offset variable like:

fn get_next_u16(input: &[u8], offset: usize) -> (usize, u16) {
   (offset+2, ((input[offset+1] as u16) << 8) +
               (input[offset]   as u16))
}

fn main() {
    let input = [1, 2, 3, 4];
    let offset = 0;
    let (offset, first_u16) = get_next_u16(&input, offset);
    let (offset, second_u16) = get_next_u16(&input, offset);
    println!("first: {}", first_u16);
    println!("second: {}", second_u16);
}

This looks cleaner but now you have to reassign to offset all the time.

Perhaps there is another way to do this also?


texts: Calculate highest prime factor very slow

texts:
Sometimes when I write a Python 3.x script with too many nested loops and some big values it just takes too long to give the answer. How can I optimize my code so that it runs faster, or where should I optimize?

def isprime(n):
    '''check if integer n is a prime'''
    # make sure n is a positive integer
    n = abs(int(n))
    # 0 and 1 are not primes
    if n < 2:
        return False
    # 2 is the only even prime number
    if n == 2:
        return True
    # all other even numbers are not primes
    if not n & 1:
        return False
    # range starts with 3 and only needs to go up the squareroot of n
    # for all odd numbers
    for x in range(3, int(n**0.5)+1, 2):
        if n % x == 0:
            return False
    return True

ans=0
for i in range(600851475143,0,-1):
if 600851475143%i==0:
    if isprime(i)==True:
        ans=i
        break;
    else:
        continue;
print(ans)

This program should calculate the highest prime factor of the number 600851475143, but it didn't give any answer for half an hour.


texts:
I inherited a lot of C code with many ellipsis (variadic) functions.

I have a lots of API with the following signature:

void getXY(int foo, ...) // many parameters

and this is used in this way as usual:

getXY(1, "sizex", 12, "sizey", 24, 0);

Now I started to think about how I can replace it with a typesafe C++ API, and I came up with the following:

#include <string>
#include <iostream>
#include <cstdarg>
#include <vector>

class Test
{
  struct GetParam
    {
      std::string name;
      int id;
    };
  struct Attr
    {
      Attr(Test& test) : test(test)
        {
          std::cout << "Attr()" << std::endl;
          test.get_params.clear();
        }
      ~Attr()
        {
          std::cout << "~Attr()" << std::endl;
          test.end_get();
        }
      Attr& add(const std::string& name, int id)
        {
          GetParam param = {name, id};
          test.get_params.push_back(param);
          return *this;
        }
      Test& test;
    };
  void end_get()
    {
      for (auto get_param : get_params)
        std::cout << "name:" << get_param.name << ", id:" << get_param.id << std::endl;
    }
  std::vector<GetParam> get_params;

public:
  // old code
  void get1(int foo, ...)
    {
      va_list args;
      va_start(args, foo);
      const char* name = va_arg(args, const char *);
      for (; name != NULL; name = va_arg(args, const char *))
        {
          int id = va_arg(args, int);
          std::cout << "name:" << name << ", id:" << id << std::endl;
        }
      va_end(args);
    }

  // new code plan
  Attr get2(int foo)
    {
      Attr attr(*this);
      return attr;
    }
private:
};

int main()
{
  Test test;
  test.get1(1, "sizex", 12, "sizey", 24, 0); // old style
  test.get2(1).add("sizex", 12).add("sizey", 24); // new style
  return 0;
}

What do you think? Is there a simpler solution? How can I improve this?


texts: DAO to create, update, and delete a project

texts:
I'm trying to write my first "complex" program in Java. So far, I created a local H2 database but I'm not sure about the quality of my code (I'm newbie in Java) because I don't know how I can deal with exceptions and I don't feel comfortable with the JDBC code.

 public boolean create(Project project)  {
 String id = UUID.randomUUID().toString().toUpperCase().replace("-", "");
 project.setId(id);

    try {
        Class.forName("org.h2.Driver");
        Connection connection = DriverManager.getConnection("jdbc:h2:~/dao_db", "sa", "");
        PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO PROJECT VALUES(?, ?,?)");

        preparedStatement.setString(1, id);
        preparedStatement.setString(2, project.getName());
        preparedStatement.setString(3, project.getTrigram());
        int resultSet = preparedStatement.executeUpdate();

        if(resultSet!=0)
        {
            System.out.println("Project created");
            connection.close();
            return true;
        }

        else {
            System.out.println("No project was  created ");
            connection.close();
            return false;
        }

    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    }
    return false;

}

@Override
public boolean update(Project project){

    try {
        Class.forName("org.h2.Driver");

        Connection connection = DriverManager.getConnection("jdbc:h2:~/dao_db", "sa", "");
        PreparedStatement preparedStatement = connection.prepareStatement("UPDATE PROJECT SET NAME=?, TRIGRAM = ? WHERE ID=?");

        preparedStatement.setString(1, project.getName());
        preparedStatement.setString(2, project.getTrigram());
        preparedStatement.setString(3, project.getId());
        int resultSet = preparedStatement.executeUpdate();

        if(resultSet==0) {
            System.out.println("The project was not updated ");
            connection.close();
            return false;
        }
        else {
            System.out.println("Project updated" + '\n'+  project.toString());
            connection.close();
            return true;
        }

    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    }
    return false;
}

@Override
public boolean delete(String id) {

    try {
        Class.forName("org.h2.Driver");
        Connection connection = DriverManager.getConnection("jdbc:h2:~/dao_db", "sa", "");
        PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM PROJECT WHERE ID=?");
        preparedStatement.setString(1,id);
        int result = preparedStatement.executeUpdate();

        if(result!=0) {

            PreparedStatement preparedStatement2 = connection.prepareStatement("DELETE FROM MILESTONE WHERE FK_PROJECT_ID =?");
            preparedStatement2.setString(1,id);
            preparedStatement2.executeUpdate();

            PreparedStatement preparedStatement3 = connection.prepareStatement("DELETE FROM REQUIREMENT WHERE FK_PROJECT_ID =?");
            preparedStatement3.setString(1,id);
            preparedStatement3.executeUpdate();

            System.out.println("Project deleted with id = " + id);
            connection.close();
            return true;

        }

        else {
            System.out.println("No project was deleted with id = " + id);
            connection.close();
            return false;
        }

    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    }
    return false;
}

As you can see, the management of the exception here is very very poor. Can you help me to optimize this? Should I use finally or something like that?
I feel that there a big redundancy in my code since that I'm obliged to write many lines to create a JDBC connection and execute a SQL query. I have 6 tables, so the quality is really poor. I don't know how can I optimize this because the query changes in each method.


texts: Find the UTF-8 Length of a given codepoint

texts:
A codepoint in UTF-8 can be represented by one to four bytes. Given a codepoint, I need to determine the length (in bytes) of the codepoint if it were represented in UTF-8. For this, I've written the following function:
char utf8_char_size(uint32_t ch) {
    if (ch < 0x80) return 1;
    if (ch < 0x800) return 2;
    if (ch < 0x10000) return 3;
    return 4;
}

It works, and it's pretty simple to understand. However, I'm afraid that branching three times per codepoint could lead to a large amount of branch mispredictions which would slow my code down tremendously. Is this code fine?


texts: Is there a better way to flatten out a multidimensional list?

texts:
def alist(x):
    if x == 1:
        return 1
    return [alist(x - 1), x, alist(x - 1)]
l = '%r' % alist(int(raw_input('Maximum Number Of Asterisks: ')))
f = l.replace("[", "").replace("]", "").replace(",", "").replace(" ", "")
for i in f:
    print "*" * int(i)

So, basically, I just formatted the list into a string, removed all unwanted characters (left bracket, right brakcer, comma, and space), and for every number in that string, printed the appropriate amount of asterisks. If there is anything you don't understand, sorry because I had to type this up in under 2 minutes, so please just post a comment and I'll try to answer as soon as I can.


texts: Renaming form controls and underlying code

texts:
I was working on adjusting some variable naming on an Excel project and ran into an issue that the MSForm control names needed to be updated. When you change the properties of the control on the form, the underlying code for the form doesn't seem to update accordingly.

Examples:

  You rename btn_button1 to btn_populateList. Now when you click the button it still wants to call btn_button1_Click() rather than
  btn_populateList_Click().
  You rename inputbox1 to listToPopulate but when you run pre-existing code, it still refers to inputbox1 instead of the new
  name of the control.

Anyhow, I've always wanted to mess around to get VBA to do stuff in the VBE, so this was my chance!

The macro finds the target project and target form and then updates the control names and appends the string NEW to oldName such that it's oldNameNEW. This was done so I could easily revert the names back using the same procedure with left(len()-3).

Ideally, the array of new names would be populated by the user with descriptive names and would be populated outside of the For loop, obviously.

I'm sure there's some clever refactoring that can be done, but I wasn't sure if I'd break it.

Also, I'm worried I misunderstand how Forms call their macros given it's not designed the same way as controls on sheets.

Public Sub FindReplaceInEntireModule()
    Const TARGET_ADDIN As String = "bUTLAddIn"
    Const TARGET_FORM As String = "form_chtGrid"

    Dim targetProject As VBIDE.VBProject
    Dim targetModule As VBIDE.VBComponent
    Dim targetCode As VBIDE.CodeModule
    Dim controlIndex As Long
    Set targetProject = Application.VBE.VBProjects(TARGET_ADDIN)

    Set targetModule = targetProject.VBComponents(TARGET_FORM)
    Dim targetForm As Object
    Set targetForm = targetModule.Designer
    Dim numberOfControls As Long
    numberOfControls = targetForm.Controls.count

    Dim newControlNames() As String
    ReDim newControlNames(1 To numberOfControls)
    Dim oldControlNames() As String
    ReDim oldControlNames(1 To numberOfControls)

    For controlIndex = 1 To numberOfControls
        oldControlNames(controlIndex) = targetForm.Controls(controlIndex).name
        newControlNames(controlIndex) = oldControlNames(controlIndex) & "NEW"
        targetForm.Controls(controlIndex).name = newControlNames(controlIndex)
    Next

    Set targetCode = targetModule.CodeModule

    Dim findWhat As String
    Dim replaceWith As String

    Dim numberOfLines As Long
    numberOfLines = targetCode.CountOfLines
    Dim lineNumber As Long
    Dim lineText As String

    For controlIndex = 1 To numberOfControls
        findWhat = oldControlNames(controlIndex)
        replaceWith = newControlNames(controlIndex)
        For lineNumber = 1 To numberOfLines
            lineText = targetCode.Lines(lineNumber, 1)
            If InStr(1, lineText, findWhat, vbTextCompare) > 0 Then
                targetCode.ReplaceLine lineNumber, Replace(lineText, findWhat, replaceWith, , , vbTextCompare)
            End If
        Next
    Next

End Sub


texts: Approximate integral in one line of code

texts:
This is what I came up with:

Version 1:

static double Integrate(Func<double, double> f, double low, double high, double delta)
{
    return Enumerable.Sum(Enumerable.Select(Enumerable.Range((int)(low / delta), (int)((high / delta) - (low / delta))), c => f(c * delta) * delta));
}

If I'm allowed to use a helper-method it becomes slightly shorter:

Version 2:

static double Integrate(Func<double, double> f, double low, double high, double delta)
{
    return Enumerable.Sum(Enumerable.Select(DoubleRange(low, high, delta), c => f(c) * delta));
}

public static IEnumerable<double> DoubleRange(double min, double max, double step)
{
    for (double value = min; value <= max; value += step)
    {
        yield return value;
    }
}

Are there any better ways to do this? It's unfortunate LINQ doesn't have an overload for Enumerable.Range that takes floating point values. Are there ways of doing this with either more efficient or less characters of code?


texts: Grouping objects that have the same attributes

texts:
A list of objects needs to be grouped.

The list is iterated and checked with other objects in the same list except itself. The method People.isAttributeEqual() checks if two objects can be grouped.

The list returns a list of two unique objects with the same attributes.

I am trying to optimize the method People.groupSimilar(). All other details given here are just snippets.

The code below works but looks clunky and non optimized. Is there a way to optimize and use lambda instead?

public class People
{

  private String name;
  private String age;
  private String address;

  public People(final String name, final String age, final String address)
  {
    this.name = name;
    this.age = age;
    this.address = address;
  }

  public boolean isAttributeEqual(final People dupPeop)
  {
    return this.address.equals(dupPeop.address) && this.age.equals(dupPeop.age) && this.name.equals(dupPeop.name);
  }

  public static void main(final String[] args)
  {

    List<People> asList = Arrays.asList(new People("Sri", "28", "TN"), new People("Sri", "28", "TN"), new People("Sri", "28", "TN"),
        new People("Pri", "28", "TN"));

    List<People> groupSimilar = groupSimilar(asList);

  }

  public static List<People> groupSimilar(final List<People> people)
  {
    List<People> duplicatePeople = new ArrayList<>(people);
    for (Iterator<People> iterator = duplicatePeople.iterator(); iterator.hasNext();)
    {
      People people2 = iterator.next();
      for (People orignalPeople : people)
      {
        if (!orignalPeople.equals(people2) && orignalPeople.isAttributeEqual(people2))
        {
          iterator.remove();
          people2 = iterator.next();
        }
      }
    }
    return duplicatePeople;
  }
}


texts: My take on the algorithmic crush problem from HackerRank

texts:
This is my solution to the Algorithmic Crush problem from HackerRank. Can I get any comments regarding where I can improve the code to be more efficient?

  You are given a list of size \$N\$, initialized with zeroes. You have
  to perform \$M\$ operations on the list and output the maximum of
  final values of all the \$N\$ elements in the list. For every
  operation, you are given three integers \$a, b\$ and \$k\$ and you
  have to add value to all the elements ranging from index \$a\$ to
  \$b\$ (both inclusive).

  Input Format

  First line will contain two integers \$N\$ and \$M\$ separated by a
  single space. Next \$M\$ lines will contain three integers \$a, b\$
  and \$k\$ separated by a single space. Numbers in list are numbered
  from \$1\$ to \$N\$.

  Constraints

  \$3 \leq N \leq 10^7\$

  \$1\leq M \leq 2*10^5\$

  \$1 \leq a \leq b \leq N\$

  \$ 0 \leq k \leq 10^9\$

  Output Format

  A single line containing maximum value in the updated list.

  Sample Input

5 3
1 2 100
2 5 100
3 4 100

  Sample Output

200

def updateList(seq, listA):
    st, end, value = map(int, seq.split())
    for i in range(st-1, end):
        listA[i] = listA[i]+value
    return listA

n, m = map(int, raw_input().split())

lis = [0 for i in range(n)]

for ins in range(m):
    cmds = raw_input()
    resultSet = updateList(cmds, lis)
    lis = resultSet
print sorted(resultSet)[-1]


texts:
This is a wolfram language program I wrote for super-resolution, in this case meaning to guess at how to increase the the resolution, and so detail shown in a raster image such as a photograph.

It uses a similar but different aproach to its successor, which is much better program, so please start with the new aproach here instead: Super Resolution in the Wolfram Language, Attempt 2

For those still on this page, both approaches are based on self similarity, exploiting large parts of images that are similar to small parts, to attempt to increase the resolution of the image.

Thease images are the original image image1, the image enlarged with simple interpolation, and the full result, using the super-resolution process.

The planks above the dog seem to be as good as it gets, the mess to the right apparently having a lower threshold.

There appeared to be a large performance hit to combining lines, using line breaks to visually show structure, the code is therefore more broken up with assignments a = ... than I'd like.

There are various possible improvements, such as having image2 broken into overlapping chunks, giving more data to match from. Or having the chunks that form the result being transparent and overlapping.

ur1 = "http://placepuppy.it/150/200";

image1url = ur1;
image1Scale = 2;
image2url = ur1;
grid = 16;
threshold = 1.5;
RQ = 1;

e = Import[image1url, "Image"];
image1 = ImageResize[e, Scaled@image1Scale];
image2 = Import[image2url, "Image"];
a = ImagePartition[image1,grid];
image1andResultImageWidth = Length@a[[1]];
image1chunks = Flatten@a;
image2chunks = Flatten@ImagePartition[image2, grid];
b = (Thread@{#, image2chunks})&;
image1Image2ChunkPairsInImage1Groups = b/@image1chunks;
chunkPairDist = ImageDistance[#[[1]], #[[2]]]&;
c = MinimalBy[#,chunkPairDist,RQ][[RQ]]&;
bestMatchForEachImage1ChunkAsPair = c/@image1Image2ChunkPairsInImage1Groups;
d = If[chunkPairDist@#<threshold, #[[2]], #[[1]]]&;
flatResultImageAsChunks = d/@bestMatchForEachImage1ChunkAsPair;
{e, image1, ImageAssemble@Partition[flatResultImageAsChunks, image1andResultImageWidth]}


texts:
I have written a program for a simple calculator that can add, subtract, multiply and divide using functions.

Here is my code:

# This function adds two numbers
def add(x, y):
   return x + y

# This function subtracts two numbers
def subtract(x, y):
   return x - y

# This function multiplies two numbers
def multiply(x, y):
   return x * y

# This function divides two numbers
def divide(x, y):
   return x / y

print ("Select operation.")
print ("1. Add")
print ("2. Subtract")
print ("3. Multiply")
print ("4. Divide")

choice = input("Enter choice (1/2/3/4): ")

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if choice == '1':
   print(num1, "+", num2, "=", add(num1,num2))

elif choice == '2':
   print(num1, "-", num2, "=", subtract(num1,num2))

elif choice == '3':
   print(num1, "*", num2, "=", multiply(num1,num2))

elif choice == '4':
   print(num1, "/", num2, "=", divide(num1,num2))
else:
   print("Invalid input")

So, I would like to know whether I could make this code shorter and more efficient.

Also, any alternatives are greatly welcome.

Any help would be highly appreciated.


texts:
This structure is supposed to iterate over the lines of an input stream, using std::getline. Any remark is welcome!

#include <iostream> //istream
#include <cassert>

struct line_iterator
{
    explicit
    line_iterator( std::istream & is )
        : m_stream( &is )
        , m_line( extract_line() )
    {
    }

    line_iterator()
        : m_stream( nullptr )
        , m_line()
    {
    }

    line_iterator( line_iterator & ) = default;

    std::string operator*()
    {
        assert( m_stream );
        return m_line;
    }

    line_iterator operator++()
    {
        assert( m_stream );
        update_stream();
        return *this;
    }

    line_iterator operator++(int)
    {
        line_iterator copy( *this );
        ++(*this);
        return copy;
    }
private:
    void update_stream()
    {
        if ( m_stream->good() )
            m_line = extract_line();

        else
        {
            m_line.clear();
            m_stream = nullptr;
        }
    }

    std::string extract_line()
    {
        std::string line;
        std::getline( *m_stream, line );
        return line;
    }

private:
    std::istream *  m_stream;
    std::string     m_line;

    friend bool operator!=( const line_iterator&, const line_iterator& );
    friend bool operator==( const line_iterator&, const line_iterator& );
};

inline
bool operator!=( const line_iterator & a, const line_iterator & b )
{
    return !(a.m_stream == b.m_stream);
}

inline
bool operator==( const line_iterator & a, const line_iterator & b )
{
    return a.m_stream == b.m_stream;
}


texts:
I created the below comparer to allow me to use a generic dictionary as a key to another generic dictionary.

My GetHashCode implementation creates a hash based on all keys and their values; but I suspect its distribution could be improved?

Also my Equals method returns true only if the two arguments have exactly the same keys, with each key having exactly the same values.  However, potentially there's a more efficient approach to this comparison which I've neglected?

using System.Collections.Generic;
using System.Linq;

namespace MyCompany.Collections.Generic
{
    public class DictionaryEqualityComparer<TKey, TValue> : IEqualityComparer<IDictionary<TKey, TValue>>
    {
        readonly IEqualityComparer<TKey> keyComparer;
        readonly IEqualityComparer<TValue> valueComparer;

        public DictionaryEqualityComparer(): this(null, null){}
        public DictionaryEqualityComparer(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
        {
            this.keyComparer = keyComparer ?? EqualityComparer<TKey>.Default;
            this.valueComparer = valueComparer ?? EqualityComparer<TValue>.Default;
        }

        public bool Equals(IDictionary<TKey, TValue> a, IDictionary<TKey, TValue> b)
        {
            if (a == null || b == null) return (a == null && b == null);                //if either value is null return false, or true if both are null
            return a.Count == b.Count                                                   //unless they have the same number of items, the dictionaries do not match
                && a.Keys.Intersect(b.Keys, keyComparer).Count() == a.Count             //unless they have the same keys, the dictionaries do not match
                && a.Keys.Where(key => ValueEquals(a[key], b[key])).Count() == a.Count; //unless each keys' value is the same in both, the dictionaries do not match
        }

        public int GetHashCode(IDictionary<TKey, TValue> obj)
        {
            //I suspect there's a more efficient formula for even distribution, but this does the job for now
            long hashCode = obj.Count;
            foreach (var key in obj.Keys)
            {
                hashCode += (key?.GetHashCode() ?? 1000) + (obj[key]?.GetHashCode() ?? 0);
                hashCode %= int.MaxValue; //ensure we don't go outside the bounds of MinValue-MaxValue
            }
            return (int)hashCode; //safe conversion thanks to the above %
        }

        private bool ValueEquals(TValue x, TValue y)
        {
            return valueComparer.Equals(x, y);
        }

    }
}


texts:
I'm learning C++ and currently doing Project Euler challenges. The first challenge is the following.

  If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

  Find the sum of all the multiples of 3 or 5 below 1000.

I did a quite simple and stupid brute-force implementation by just looping from 1 to 999, checking if its divisible by either 3 or 5 and if it is, sum it with the result variable.

Is there any faster/better/cleaner implementation, maybe without a loop or with less division?

#include <iostream>

int main(int argc, char *argv[])
{
    int result(0);
    for (int i = 1; i < 1000; ++i) {
        if (!(i % 3 && i % 5)) {
            result += i;
        }
    }
    std::cout << "Result: " << result << "\n";
    return 0;
}


texts: C++ Super Simple HTML Tag Generating Code v0.1

texts:
I made this simple code which makes easy HTML tag generation. It is open-source and right now only makes tag names and replaces tags... :/

#include <iostream>
#include <fstream>

std::string makeHtmlTags(std::string tagname, std::string tagcontent) {
    return "<" + tagname + ">" + tagcontent + "</" + tagname + ">";
}

void changeHtmlTag(std::string * tag, std::string newtagname)
{
    if(tag->at(2) != '/')
        *tag = "<" + newtagname + ">";
    else
        *tag = "</" + newtagname + ">";
}

int main()
{
    std::string html = makeHtmlTags("hello", "world");
    std::string tag1 = html.substr(2, 5);
    changeHtmlTag(&tag1, "goodbye");
    changeHtmlTag(&tag1, "/goodbye");
    std::cout << tag1;
}

What can I do to make it more useful?


texts:
I'm trying to figure out if there's a better way to run the code below.
Basically Course is an association of Student and courses_needed is an array of Course where I have many Students have and need many Courses and I'm trying to figure out the demand.
I've came up with the following code and it runs, which is fine, but when I want to display it on a statistics page with 36 Courses, the same code needs to be run once for each Course.

I've solved it now by having it run once a day, instead of real-time.

  def self.calculate_needed
    Course.all.each do |course|
      neededArray = Array.new
      needed = 0
      Student.all.each do |s|
        unless s.courses_needed.nil?
          s.courses_needed.each do |c|
            if c == course
              needed += 1
            end
          end
        end
      end
      course.needed = needed
      course.save
    end
  end


texts: OOP, FP and IMP condensed in Rock, Paper and Scissors

texts:
Rock Paper and Scissors is a pretty basic program.

The reason I wrote this program is because I wanted to see what a small script that used all of the main programming paradigms looked like.

My code contains:

OOP: A Player object.
FP: First class functions : player.intelligence is a function is stored in a variables and I use anonymous lambdas
IMP: The code asks for input freely, asking for input freely in a functional paradigm is not possible, so this is the imperative part.

Tell me if you like it or if you think it is too complex for an easy task and should be simplified.

from collections import namedtuple
import random

RPS = ["rock", "paper", "scissors"]

Player = namedtuple('Player', 'name intelligence')

def rock_paper_scissors(player_1, player_2):
    a, b = player_1.intelligence(), player_2.intelligence()
    print("\n{} chose {}\n{} chose {}\n".format(
        player_1.name, RPS[a-1], player_2.name, RPS[b-1]))
    return "Tie" if a == b else \
      "The winner is " + (player_1.name if (a - b) % 3 == 1 else player_2.name)

def human_intelligence(prompt):
    return RPS.index(input("The Player 1 move: ").lower())+1

def random_ai():
    return random.choice((1,2,3))

Human vs Computer

print(rock_paper_scissors(
    Player("The Human", lambda: human_intelligence("The human's move : ")),
    Player("The Computer", random_ai)
    )
)

Human vs Human

print(rock_paper_scissors(
    Player("The Player 1", lambda: human_intelligence("Player 1 move : ")),
    Player("The Player 2", lambda: human_intelligence("Player 2 move : "))
    )
)

Computer vs Computer

print(rock_paper_scissors(
    Player("The Computer 1", random_ai),
    Player("The Computer 2", random_ai)
    )
)


texts:
Is this an efficient and clean implementation?

function BST(items) {
    this.tree = {};
    if (items) items.forEach(this.add, this);
}

BST.prototype.add = function(item) {
    if (!this.tree.value) {
        this.tree.value = item;
        return item;
    }
    var currNode = this.tree;
    var inserted = false;
    while (!inserted) {
        if (item > currNode.value) {
            if (currNode.rightNode) currNode = currNode.rightNode;
            else {
                currNode.rightNode = {
                    value: item
                };
                inserted = true;
            }
        } else {
            if (currNode.leftNode) currNode = currNode.leftNode;
            else {
                currNode.leftNode = {
                    value: item
                };
                inserted = true;
            }
        }
    }
    return item;
};

BST.prototype.printTree = function() {
    console.log(this.tree);
};


texts: Building array of 'truthy' rule conditions

texts:
I'm running a lot of functions to build a mongoDb request. Based on their response (if not falsy) I'm appending the return values to an array ruleConditions[] which is used later.

Currently I'm doing it this way:

//building ruleConditions
var ruleConditions = {$and: []};

var fromConditions = mongoRequestsHelper.getFromConditions(rule.from);
if (fromConditions) ruleConditions.$and.push(fromConditions);

//and 4 similar blocks

Is there any way to avoid unneeded variables creation (carTypesConditions...)?

Calling functions twice like:

if (mongoRequestsHelper.getFromConditions(rule.moversFilter)) ruleConditions.push(mongoRequestsHelper.getFromConditions(rule.moversFilter))

is not a good idea obviously.


texts:
My aim was to create a function which behaves like the operator . in Haskell.

Here is what I made:

template <typename F>
auto compose(F&& f)
{
    return [a = std::move(f)](auto&&... args){
        return a(std::move(args)...);
    };
}

template <typename F1, typename F2, typename... Fs>
auto compose(F1&& f1, F2&& f2, Fs&&... fs)
{
    return compose(
        [first = std::move(f1), second = std::move(f2)]
        (auto&&... args){
            return second(first(std::move(args)...));
        },
        std::move(fs)...
    );
}

Possible usage:

int main()
{
const auto f = compose([](const auto a, const auto b){return a + b;},
                       [](const auto n){return n * n;},
                       [](const auto n){return n + 2;});
std::cout << f(3, 2) << std::endl;
// should output 27 ( (3 + 2) * (3 + 2) + 2 )
}

The full source with a few more examples may be found here.

I'm not sure whether to use std::move or std::forward. Which one is better? Any other suggestions?


texts: C# program which measures the distance between the average and maximum/minimum temperature

texts:
The program below takes inputs for the temperature in various cities in a span of multiple days. It then outputs the ones where the minimal temperature is closer to the average than the maximal temperature, prefaced by the number of cities where this happens.

For example:
"3 5
10 15 12 10 10

11 11 11 11 20

12 16 16 16 20"

returns "2 1 2".

I've ran it with various particularly large inputs a few times, and the program seems to slow down with larger numbers. Is there any way to make the program faster?

class Program
    {
        static void Main(string[] args)
        {
            string input = Console.ReadLine();
            string[] inputs = input.Split();
            int cities = Convert.ToInt32(inputs[0]);
            int days = Convert.ToInt32(inputs[1]);
            int[] content = new int[days];
            int i = 0;
            int y = 0;
            float max = 0;
            float average = 0;
            float min = 50;
            int how_many = 0;
            List<int> which = new List<int>();
            for (i = 0; i < cities; i++)
            {
                input = Console.ReadLine();
                inputs = input.Split();
                for (y = 0; y < days; y++)
                {
                    content[y] = Convert.ToInt32(inputs[y]);
                    average += content[y];
                    if (content[y] > max)
                    {
                        max = content[y];
                    }
                    if (content[y] < min)
                    {
                        min = content[y];
                    }
                }
                average = (float)average / days;

                if (max - average > average - min)
                {
                    how_many += 1;
                    int position = i + 1;
                    which.Add(position);
                }
                max = 0;
                average = 0;
                min = 50;
                y = 0;

            }
            Console.Write(how_many + " ");
            i = 0;
            for (i = 0; i < which.Count(); ++i)
            {
                Console.Write(which[i] + " ");
            }

            Console.ReadKey();
        }
    }


texts:
This is for Project Euler question 18 and I'm looking for feedback on whether my algorithm is incorrect or whether I've just implemented it wrong (which I don't think is the case after some testing).

The question is to traverse the maximum path in a triangle from top to bottom.

                            75
                          95  64
                        17  47  82
                      18  35  87  10
                    20  04  82  47  65
                  19  01  23  75  03  34
                88  02  77  73  07  63  67
              99  65  04  28  06  16  70  92
            41  41  26  56  83  40  80  70  33
          41  48  72  33  47  32  37  16  94  29
        53  71  44  65  25  43  91  52  97  51  14
      70  11  33  28  77  73  17  78  39  68  17  57
    91  71  52  38  17  14  91  43  58  50  27  29  48
  63  66  04  68  89  53  67  30  73  16  69  87  40  31
04  62  98  27  23  09  70  98  73  93  38  53  60  04  23

Starting from the second bottom row, each value is its current value + max(left child, right child), which transforms each position in the tree to be its max path sum from that point.

#include <iostream>
#include <fstream>
#include <iterator>
#include <sstream>
#include <vector>

using namespace std;
using Tree = vector<vector<int>>;

void transform_mps(Tree& tree) {
    // start from bottom up, each node's value is node.val + max(left child, right child)
    // transforms tree such that each node is that node's max path sum
    for (int layer = tree.size() - 2; layer >= 0; --layer) {
        for (size_t pos = 0; pos < tree[layer].size(); ++pos) {
            tree[layer][pos] = tree[layer][pos] + max(tree[layer+1][pos], tree[layer+1][pos+1]);
        }
    }
}

int main(int argc, char* argv[]) {
    if (argc < 2) { cout << "Need to pass in file to read from\n"; return 1; }

    ifstream f {argv[1]};
    if (!f.is_open()) { cout << "Could not open file\n"; return 1; }

    Tree tree;
    string line;
    while (getline(f, line)) {
        istringstream is {line};
        tree.push_back(vector<int>(istream_iterator<int>(is), istream_iterator<int>()));
    }
    transform_mps(tree);
    int mps {tree[0][0]};
    cout << "Max path sum: " << mps << endl;
}

/********** leftovers from previous implementation, ignore
constexpr bool LEFT {false};
constexpr bool RIGHT {true};

int pathsum(Tree& tree, size_t layer, size_t pos, bool right) {
    int sum {};
    ++layer;    // next level
    for (; layer < tree.size(); ++layer)
        if (right) sum += tree[layer][++pos];
        else sum += tree[layer][pos];
    return sum;
}
***********/


texts:
I want to run all the coroutines from the list in a pool of constant size and would like to ask if this is the right way how to achieve it. Is there any built in solution for this problem? I have not found any.

def subprocess_pool(coroutines, pool_size=3):
    loop = asyncio.get_event_loop()
    event_finished = asyncio.Event()

    def done(future):
        event_finished.set()

    @asyncio.coroutine
    def scheduler(coroutines):
        num = len(coroutines)
        finished = 0
        started = 0
        while finished<num:
            if coroutines and (started - finished) < pool_size:
                cor = coroutines.pop(0)
                task = loop.create_task(cor)
                task.add_done_callback(done)
                started += 1
            else:
                yield from event_finished.wait()
                event_finished.clear()
                finished += 1
        return True

    loop.run_until_complete(scheduler(coroutines))
    loop.close()


texts:
I'm pretty new to working with databases, and I would like to know if I've made some common, major design flaws in my implementation. For context, the whole project is intended to be used by a single user.

The code I want reviewed:

class DatabaseConnection
{
    //properties
    private MySqlConnection _connection;
    public MySqlConnection Connection { get { return _connection; } }
    public AccountLogin AccountCredentials { get; }
    public DatabaseLogin DatabaseCredentials { get; }

    //constructor
    public DatabaseConnection(AccountLogin _AccCred,
                              DatabaseLogin _DBCred)
    {
        AccountCredentials = _AccCred;
        DatabaseCredentials = _DBCred;
    }

    public void Connect()
    {
        if (Connection != null)
        {
            return;
        }

        string[] UserInputs =
        {
            DatabaseCredentials?.DatabaseName,
            DatabaseCredentials?.Server,
            DatabaseCredentials?.Port,
            AccountCredentials?.Password,
            AccountCredentials?.Username
        };
        bool ChkInpts = Validators.NullStringValidator(UserInputs);

        if (!ChkInpts)
        {
            string ConnInfo = "server=" + DatabaseCredentials.Server + ";" +
                              "user=" + AccountCredentials.Username + ";" +
                              "database=" + DatabaseCredentials.DatabaseName +
                              "port=" + DatabaseCredentials.Port +
                              "password=" + AccountCredentials.Password;
            _connection = new MySqlConnection(ConnInfo);

            try
            {
                Console.WriteLine("Connecting to " + DatabaseCredentials.DatabaseName + "...");
                _connection.Open();
                Console.WriteLine("Connection to " + DatabaseCredentials.DatabaseName + " successful.");
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
    public void Close()
    {
        _connection.Close();
    }
}

Relevant code:

class AccountLogin
{
    public string Username { get; }
    public string Password { get; }

    public AccountLogin(string _username, string _password)
    {
        Username = _username;
        Password = _password;
    }
}

class DatabaseLogin
{
    public string DatabaseName { get; }
    public string Server { get; }
    public string Port { get; }

    public DatabaseLogin(string _server, string _DatabaseName, string _port)
    {
        DatabaseName = _DatabaseName;
        Server = _server;
        Port = _port;
    }
}

static class Validators
{
    public static bool NullStringValidator(string[] _inputs)
    {
        bool _result = false;
        for (int i = 0; i < _inputs.Length; i++)
        {
            if (string.IsNullOrEmpty(_inputs[i]))
            {
                return _result = true;
            }
        }
        return _result;
    }
}


texts: Returning a string representation of the number of albums and songs available

texts:
What this method should do is return a String that displays how many albums and songs there are. This method is a private method of my Artist class which has a method called albumCount() and songCount(). The whole class probably needs an improvement but I will try that later. First I'd like this single method to be improved if possible.

public String toAlbumSongCount() {
    StringBuilder builder = new StringBuilder();

    final int albumCount = albumCount();
    final int songCount = songCount();

    builder.append( albumCount );
    //Append albums instead of album if albumCount is greater than 1
    builder.append( (albumCount > 1) ? " albums" : " album" );
    builder.append( "," ); //Move this to the line above?
    builder.append( songCount );
    //Append songs instead of song if songCount is greater than 1
    builder.append( (songCount > 1 ) ? " songs" : " song" );

    return builder.toString();
}

I used the StringBuilder class because I heard a dozen of times that it will improve performance when concatenating Strings.
I wasn't sure about those two lines :

builder.append( (albumCount > 1) ? " albums" : " album" );
builder.append( (songCount > 1 ) ? " songs" : " song" );

Are they good enough with the comments above them?

I appreciate any help even if it means completely rewriting this method.


texts:
I have a string like "food | dairy | milk". The string may consist of more or less words. How do I turn it into a dictionary {'food': {'dairy': {'milk': {'eco': {}}}}}?

The only way I could achieve it was to create a string and then turn it into a dictionary using exec. I understand it's messy. How could I improve on it?

#!/usr/bin/env python -tt
# -*- coding: utf-8 -*-
# I have a string that represents 'path' to place where new item should be inserted
st="food | dairy | milk"
print st,"< -- string"
keys=st.split(" | ")
print keys,"<-- keys"

new_cat="eco" # should be added
d = {i:{} for i in keys}
print d,"d"

ex_str="{"
for i in keys:
    ex_str+="\""+i+"\":{"
ex_str+="\""+str(new_cat)+"\":{}"+"}"*(len(keys)+1)
exec"nd="+ex_str
print nd,"<-- new dict"


texts:
I am trying a stack implementation using an array. I want to know if this approach is OK or if there is a logical problem. This program is working fine.

#include <stdio.h>
#define MAXSIZE 5

struct stack            /* Structure definition for stack */
{
    int stk[MAXSIZE];
    int top;
} s;

void push ();
void pop();
void display ();
void search();

int main(){

int element, choice;

s.top = -1;

clrscr();

while (1)
    {
        printf ("------------------------------------------\n");
        printf ("1. PUSH\n");
        printf ("2. POP\n");
        printf ("3. DISPLAY\n");
        printf ("4. SEARCH\n");
        printf ("5. EXIT\n");
        printf ("------------------------------------------\n");

        printf ("Enter your choice\n");
        scanf   ("%d", &choice);

        switch (choice)
        {
            case 1: push();
                break;
            case 2: pop();
                break;
            case 3: display();
                break;
            case 4: search();
                break;
            case 5: return;
        }

}

}

/*Function to add an element to the stack*/
void push() {
    int num;

    if (s.top == (MAXSIZE - 1))
    {
        printf ("Error: Overflow\n");
    }
    else
    {
        printf ("Enter the element to be pushed\n");
        scanf ("%d", &num);
        s.top = s.top + 1;
        s.stk[s.top] = num;
    }
}

/*Function to delete an element from the stack*/
void pop ()
{
    int num;
    if (s.top == - 1)
    {
        printf ("Error: Stack Empty\n");
    }
    else
    {
        num = s.stk[s.top];
        printf ("poped element is = %d\n", num);
        s.top = s.top - 1;
    }
}

/*Function to display the status of the stack*/
void display()
{
    int i;
    if (s.top == -1)
    {
        printf ("Error: Stack Empty\n");
    }
    else
    {
        printf ("\nItems in Stack\n");
        for (i = s.top; i >= 0; i--)
        {
            printf ("%d\n", s.stk[i]);
        }
    }
    printf ("\n");
}

void search(){

    int i;
    int num;
    int counter=0;
    if (s.top == -1)
    {
        printf ("Error: Stack Empty\n");
    }
    else
    {
        printf ("Enter the element to be searched\n");
        scanf ("%d", &num);

        for (i = s.top; i >= 0; i--)
        {
            if(num==s.stk[i]) {
            counter++;
            break;
            }
        }

        if(counter>0){
            printf ("Element %d found in stack\n", num);
        }
        else {
            printf ("Element %d not found in stack\n", num);
        }
    }
    printf ("\n");

}


texts: Idiom: replacing a slice with a suffix of that slice (write_all loop)

texts:
As you probably already know, the Unix I/O primitive write is not guaranteed to write out all of the data in the buffer you give it; you may be obliged to loop calling it on successive suffixes of the buffer until it's all gone.  I'm trying to work out the cleanest way to write that loop in Rust.  This is what I have:

use ::nix;
use ::std::os::unix::io::RawFd;

pub fn write_all (fd: RawFd, s: &[u8]) -> nix::Result<()>
{
    use ::libc::{write, c_void};
    let mut p = s;
    while p.len() > 0 {
        let consumed = unsafe {
            write(fd, p.as_ptr() as *const c_void, p.len())
        };
        if consumed < 0 {
            return Err(nix::Error::last());
        }
        if (consumed as usize) >= p.len() { break }
        let (_, x) = p.split_at(consumed as usize);
        p = x;
    }
    Ok(())
}

This does the job, but this piece seems inelegant and I can't figure out a better way to write it:

        if (consumed as usize) >= p.len() { break }
        let (_, x) = p.split_at(consumed as usize);
        p = x;

The if eliminates a panic case that should be impossible (because write will never return a value greater than p.len()); I could live without it, but what I want here is for split_at to give me an empty trailing slice if the split point is at or beyond the end of the input.

The intermediate variable x is necessary because you can't write

        (_, p) = p.split_at(consumed as usize);

and I can't rebind p directly, because the loop control expression wouldn't see the change.

What suggestions do you have?


texts:
I just started learning Python this week and put this together for my first program (outside of a Hello World one). Does anyone have any feedback/suggestions for improvement for this? I've tried to forsee potential user input issues but I'd love to hear some thoughts from people who know what they are doing!

import random
guessesTaken = 0
# sets the guess counter
print ('Hello! What is your name?')
name = input()
# intro for user
print ('Hi, ' + name + ', I am thinking of a number between 1 and 100.' "\n" 'Do you want to try to guess my number? Please type yes or no.')
play = input()
# user inputs whether or not they want to play

while play != 'yes' and play != 'no':
    print ("I'm sorry, I didn't understand that. Please type yes or no.")
    play = input ()
# provision for invalid user input: if the input is not yes or no, they will be prompted to re-enter

    while play == 'yes':
    # the game continues
        number = random.randint (1,100)
    # the number will be between 1 and 100
        while guessesTaken < 20:
            print ('Take a guess!')
    # sets a max of 20 guesses
            try:
                guess = int(input())
            except:
                print ("I'm sorry, I didn't understand that. Please type a number between 1 and 100.")
                continue
    # provision for invalid input - if input is not an integer, user will be prompted to re-enter input
            guessesTaken += 1
    # adds to the guess counter
            if guess < number:
                print ('Your guess is too low!' "\n" 'Try again. You have ' + str(20-guessesTaken) + ' guesses left.')
            elif guess > number:
                print ('Your guess is too high!' "\n" 'Try again. You have ' + str(20-guessesTaken) + ' guesses left.')
            elif guess == number:
                break
    # if the guess is too high or too low, the loop continues. If the user guesses right, the loop ends
        if guess == number:
            print ('You got it right!' "\n" 'It only took ' + str(guessesTaken) + ' guesses!')
    # in case of correct guess within the allowed number of tries
        else:
            print ('Sorry, the number I am thinking of is ' + str(number) + '.')
    # if the user exceeds the number of guesses allowed
        guessesTaken = 0
    # resets guess counter
        print ('That was fun, ' + name + '! Want to play again?' "\n" 'Please type yes or no.')
        play = input ()

# asks if user wants to play again, with provision for invalid input
if play == 'no':
    print ("That's too bad, see you next time!")
# ends the game


texts:
Please critique this very, very basic routine which returns the length of a given char buffer or "string."

strlen: ; NOTE: RDI IS THE DEFAULT SRC FOR SCASB
    push rdi
    push rcx
    xor rcx, rcx
    mov rcx, -1

    xor al, al
    cld

    repne scasb
    neg rcx
    sub rcx, 1
    mov rax, rcx
    pop rcx
    pop rdi
    ret


texts:
I previously posted a Reservoir-Sampling program, which was basically a test version of this one. This is an assignment.  In the code below, I use RunTimeException to control when scanner finishes reading data. Reasons for this being:

I cannot use any other library than java.lang.
I cannot use Scanner, either.  We have been provided a StdIn class which has a static scanner.next() method only for reading strings.

Note: All the code is inside main() because that is how the API demands it.

Can someone review my code, and possibly tell if there's some way I can improve this?

import java.io.BufferedInputStream;
import java.util.Scanner;

public class Subset {

    public static void main(String[] args) {
        int k = Integer.parseInt(args[0]);
        String[] arr = new String[k];
        int i = 0;
        String str;
        while((str=stdin.readString())!=null && i < arr.length){
            arr[i++] = str;
            // System.out.println(str);
        }
        try{
            for(; (str=stdin.readString())!=null; i++){
                int r = (int)(Math.random()*(i + 1));
                if(r < k){
                    arr[r] = str;
                    //System.out.println(str);
                }
            }
        }catch(RuntimeException e){ // do nothing }
        for(String s : arr){
            System.out.print(s + " ");
        }
        System.out.println("\n");
    }
}
class stdin{
    private stdin(){}
    private static Scanner sc = new Scanner(new BufferedInputStream(System.in));
    public static String readString(){
        return sc.next();
    }
}

Command line input: echo A B C D E F G H I J | java Subset 3
Output: A F C

To clear out confusion, I am posting what the API and the instructor demands:

Subset client. Write a client program Subset.java that takes a command-line integer k,
reads in a sequence of N strings from standard input using StdIn.readString(),
and prints out exactly k of them, uniformly at random. Each item from the sequence can be printed out at most once.
You may assume that k = 0 and no greater than the number of string on standard input.

% echo A B C D E F G H I | java Subset 3       % echo AA BB BB BB BB BB CC CC | java Subset 8
C                                              BB
G                                              AA
A                                              BB
                                               CC
% echo A B C D E F G H I | java Subset 3       BB
E                                              BB
F                                              CC
G                                              BB
Your client should use only constant space plus one object either of type Deque or of type RandomizedQueue;
use generics properly to avoid casting and compiler warnings. It should also use time and space proportional to
at most N in the worst case, where N is the number of strings on standard input.
(For an extra challenge, use space proportional to k.) It should have the following API.

public class Subset {
   public static void main(String[] args)
}


texts: Representing a recursive data structure as HTML DIVs

texts:
I am using the following code which recursively executes function findWpisInZone(), code works fine, I just wondering if there is any better way to do it in JS,

DomBuilder.prototype = {
            domTree: '',
            findWpis: function () {
                var dataState = dojo.global.xxx.state.data,
                    scope = this;
                for (var zone in dataState) {
                    for (var wpi in dataState[zone]) {
                        this.domTree += '
'.format(zone);
                        findWpisInZone(dataState[zone][wpi]);
                        this.domTree += '
';
                    }
                }
                function findWpisInZone(wpi, type) {
                    scope.domTree += '
'.format(wpi.wpi.webpart_cid);
                    for (var zone in wpi.zones) {
                        scope.domTree += '
'.format(zone)
                        for (var wpiInner in wpi.zones[zone]) {
                            // recursion search
                            findWpisInZone(wpi.zones[zone][wpiInner], type);
                        }
                        scope.domTree += '
';
                    }
                    scope.domTree += '
';
                }
            },


texts:
I have these following controller functions for registering a user and login, in my app, and I want to make it more clean and maintainable.

Probably by using async/await and exec().  Also, the validations do not look not good. It would be great if you suggested me good practices to refactor this.

   registerUser: (req, res) => {
        const { username, email, password } = req.body
        User.create(req.body, (err, createdUser) => {
            if (err) {
                return res.status(500).json({ error: "Server error occurred" })
            } else if (!username || !email || !password) {
                return res.status(400).json({ message: "Username, email and password are must" })
            } else if (!validator.isEmail(email)) {
                return res.status(400).json({ message: "Invaid email" })
            } else if (password.length < 6) {
                return res.status(400).json({ message: "Password should be of at least 6 characters" })
            }
            else {
                return res.status(200).json({ user: createdUser })
            }
        })
    },

    loginUser: async (req, res, next) => {
        const { email, password } = req.body

        if (!email || !password) {
            return res.status(400).json({ message: "Email and password are must" })
        }

        await User.findOne({ email }, (err, user) => {
            if (err) {
                return next(err)
            } else if (!validator.isEmail(email)) {
                return res.status(400).json({ message: "Invalid email" })
            } else if (!user) {
                return res.status(402).json({ error: "User not found" })
            } else if (!user.confirmPassword(password)) {
                return res.status(402).json({ error: "incorrect password" })
            }

        })
    }
```


texts: pattern matching, replacement and for loop optimization in R

texts:
0
down vote
favorite

I have two data frame loc_df and and city_df (city and country) now loc_df has 5 column but considering only 2 here (Organization.Location.1 and Organization.Location.2) with 35000 row and city_df has 2 column (city and country) with 1000 rows. Now I am taking one value from city cloumn and matching with organisation column using grepl (for text matching ) and for loop(for iteration). I also have to maintain a index that's why I am using for loop. But this is taking huge amount of time.

I am trying to replace each city, state, province name to their country name in organization columns.

Please help me to optimize this code. I am very new to R.

for(k in 1:2){
  if(k==1){

    for (i in 1:nrow(city_df)) {
      x1 <- paste(" ", city_df$City[i], sep = "")
      x2 <- paste(" ", city_df$City[i], " ", sep = "")
      x3 <- paste(city_df$City[i], " ", sep = "")
      # print(x1)

      for (j in 1:nrow(loc_df)) {
        #print(loc_df$Organization.Location.1[j])

        if (grepl(x1, loc_df$Organization.Location.1[j]) |
            grepl(x2, loc_df$Organization.Location.1[j]) |
            grepl(x3, loc_df$Organization.Location.1[j])) {
            loc_df$org_new1[j] <- city_df$Country[i]
          break

        }

      }
    }
  }
  if(k==2){

    for (i in 1:nrow(city_df)) {
      x1 <- paste(" ", city_df$City[i], sep = "")
      x2 <- paste(" ", city_df$City[i], " ", sep = "")
      x3 <- paste(city_df$City[i], " ", sep = "")

      for (j in 1:nrow(loc_df)) {

        if (grepl(x1, loc_df$Organization.Location.2[j]) |
            grepl(x2, loc_df$Organization.Location.2[j]) |
            grepl(x3, loc_df$Organization.Location.3[j])) {
            loc_df$org_new1[j] <- city_df$Country[i]
          break

        }

      }
    }
  }

}

this is sample data I have generated using dput of city_df

structure(list(City = c("zug", "canton of zug", "zimbabwe",
                                  "zigong  chengdu", "zhuhai  guangdong  china", "zaragoza  spain"), Country = c("switzerland",
                                                                                "switzerland", "zimbabwe", "china", "china", "spain"
                                  )), .Names = c("City", "Country"), row.names = c(NA, 6L), class = "data.frame")

sample of loc_df

structure(list(Organization.Location.1 = c("zug  switzerland",
"zug  canton of zug  switzerland", "zimbabwe", "zigong  chengdu  pr china",
"zhuhai  guangdong  china", "zaragoza  spain"), Organization.Location.2 = c("",
"san francisco bay area", "london  canada area", "beijing city  china",
"greater atlanta area", "paris area  france")), .Names = c("Organization.Location.1",
"Organization.Location.2"), row.names = c(NA, 6L), class = "data.frame")


texts: Count cars passing in opposite directions

texts:
The problem comes from codility, whose coding problems I'm starting to enjoy as their evaluation criteria really looks at runtime.

Task description

  A non-empty zero-indexed array A consisting of N integers is
  given. The consecutive elements of array A represent consecutive
  cars on a road.

  Array A contains only 0s and/or 1s:

  0 represents a car traveling east,
  1 represents a car traveling west.

  The goal is to count passing cars. We say that a pair of cars (P, Q),
  where 0 ≤ P < Q < N, is passing when P is traveling to the east and
  Q is traveling to the west.

  For example, consider array A such that:

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

  We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3),
  (2, 4).

  Write a function:

def solution(a)

  that, given a non-empty zero-indexed array A of N integers, returns the number of passing cars.

  The function should return −1 if the number of passing cars exceeds
  1,000,000,000.

  For example, given:

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

  the function should return 5, as explained above.

  Assume that:

  N is an integer within the range [1..100,000];
  each element of array A is an integer that can have one of the following values: 0, 1.

  Complexity:

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

  Elements of input arrays can be modified.

Solution

I've tried my hand at 2 different solutions, one where I delete elements from the array but that was slower than my first pass like this:

def solution(a)
  results = 0
  a.each_with_index do |el, i|
    if el == 0
      j = i
      while j <= a.size-1
        results += 1 if a[j] != 0
        j += 1
      end
    end
    return -1 if results > 1000000000
  end
  results
end

I understand why this is \$O(n^2)\$, but I'm unsure how to make this faster.


texts: Project Euler 92: sum of squares of digits until a loop is encountered

texts:
This is my solution to Project Euler #92:

  A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before.

  For example,

  44 → 32 → 13 → 10 → 1 → 1
  85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89

  Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89.

  How many starting numbers below ten million will arrive at 89?

I was wondering how the code looks from a Pythonic perspective: is there anything that could be better? Cleaner? Is there anything that can be improved upon from a performance perspective?

from itertools import (
    islice,
    combinations_with_replacement,
    groupby
)
import operator

def get_digits(num):
    for c in str(num):
        yield int(c)

def sum_sq_digits(d):
    return sum(i*i for i in d)

def memoize(f):
    cache = {}
    def wrapped(*args):
        if args not in cache:
            cache[args] = f(*args)
        return cache[args]
    return wrapped

@memoize
def sum_sq_chain(num):
    if num in (1, 89):
        return num

    return sum_sq_chain(sum_sq_digits(get_digits(num)))

def fact(i):
    return reduce(operator.mul,
        xrange(1, i+1),
        1)

count = 0
for digits in islice(
        combinations_with_replacement(range(10), 7),
        1,
        None):

    if sum_sq_chain(sum_sq_digits(digits)) == 89:
        cur = fact(7)
        for _, v in groupby(digits):
            cur //= fact(len(list(v)))
        count += cur

print count


texts: Any performance difficulties related to List?

texts:
I'm using the following structure:

class Map
{
    public List<List<Point>> points;
    public List<Base> bases;
}

Point and Base are over-normal sized classes (has more than 30 attributes).

And I'm iterating this Map class like this:

public static void calculateMatrix(Map map)
{
    LineOfSight.LineOfSight los = new LineOfSight.LineOfSight();

    foreach (var b in map.bases)
    {
        foreach (var cc in map.points)
        {
            foreach (var c in cc)
            {
                calculatePointValues(c, b, los);
            }
        }
    }
}

There is around 500*500 points List<List<T>> and around 10 bases.

This iterating is calling calculatePointValues method around 2.5 million.

And my application can be initiated around 30 seconds.

Shall I use Array instead of List<>?
Shall I use for() instead of foreach?

Or, what should I do?


texts: DailyProgrammer Balancing Words Challenge

texts:
I'm hoping for someone to help me use the best practices and further make my code better that I used to accomplish the DailyProgrammer Challenge "Balancing Words".

The challenge is to check if a word will "balance" and if it will, where it balances. For a word to balance at a letter, all of the weight to the left and to the right of the letter have to be equal. Weight is calculated by the letter's index in the alphabet (A = 1, B = 2 ... Z = 26) multiplied by the letter's distance from the balance point.

For example, with the input of STEAD, the program should output "S T EAD - 19" since STEAD balances at the T. The left hand side of T is just S. S = 19(th letter in the alphabet) * 1(distance from T) = 19. The right hand side of T is EAD = 1 * 5 + 2 * 1 + 3 * 4 = 19. Since both sides are 19 when T is the middle, T is the balance point so I print out the word STEAD with spaces around T "S T EAD" and the weight of either side (since they're equal) " - 19".

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    /*
     * Enter multiple lines of input separated by '\n', when a line is empty stop collecting input.
     */
    cout << "Enter input in capital letters, just press enter to stop." << endl;
    vector<string> input;
    string inputLine;
    while (getline(cin, inputLine)) {
        if (inputLine != "") {
            input.push_back(inputLine);
        }
        else {
            break;
        }
    }

    /*
     * This initial for loop is just cycling
     * through all of the words from the input.
     */
    bool balances = false;
    for (string &word : input) {
        /*
         * This for loop goes through all of
         * the letters in the current word.
         */
        for (int i = 0; i < word.length(); ++i) {
        int leftWeight = 0;
        int rightWeight = 0;
            /*
             * This loop goes through all of the letters to the left
             * of the currently selected "balance point" and calculates
             * the total "weight" on the left side.
             */
            for (int j = 0; j < i; ++j) { // Left of index
                leftWeight += (1 + word[j] - 'A') * (i - j);
            }
            /*
             * Same as above, but for the right-side of the "balance point."
             */
            for (int j = i; j < word.length(); ++j) {
                rightWeight += (1 + word[j] - 'A') * (j - i);
            }

            balances = leftWeight == rightWeight;
            /*
             * This exits out as soon as the working "balance point" is found!
             */
            if (balances) {
                cout << word.substr(0, i) << " " << word[i] << " " << word.substr(i + 1, word.length()) << " - " << leftWeight << endl;
                break;
            }
        }
        if (!balances) {
            cout << word << " DOES NOT BALANCE." << endl;
        }
        cout << endl;
    }
}


texts: Reduction of time for the code of sorting RGB and Depth images according to timestamp values

texts:
I have RGB Images, Depth images and OpenPose Images(generated from RGB Images).
The number of RGB and Depth images are different so I have to find the exactly which RGB images corresponds to which depth images. This is done using the time stamp values I have for both RGB and Depth Images.

The problem here is this code I have written takes around 7-10 minutes to execute which I feel is a lot. How can the time be reduced for the same? Here mainly imwrite is taking lot of time.

function image_sorting(color_img, depth_img, Openpose, selected_color, selected_depth)

filePattern = fullfile(depth_img, '*.timestamp');
file = dir(filePattern);

filePattern2 = fullfile(color_img, '*.timestamp');
file2 = dir(filePattern2);

filePattern3 = fullfile(depth_img, '*.bmp');
file3 = dir(filePattern3);

filePattern4 = fullfile(Openpose, '*.png');
file4 = dir(filePattern4);

for k = 1:length(file)
    depthTimestampBase = file(k).name;
    depthTimestamp = fullfile(depth_img, depthTimestampBase);
    fileID = fopen(depthTimestamp,'r');
    % format longG
    A(k,:) = textscan(fileID,'%d64') ;
    fclose(fileID);
end

for m = 1:length(file2)
    rgbTimestampBase = file2(m).name;
    rgbTimestamp = fullfile(color_img, rgbTimestampBase);
    fileID2 = fopen(rgbTimestamp,'r');
    %format longG
    B(m,:) = textscan(fileID2,'%d64') ;
    fclose(fileID2);
end

%%%%%% Here there are two parts. Use any of them according to conditions
if length(file2) <= length(file)
    %PART 1:- If RGB images are less than depth then use the following code

    for m = 1:length(file2)
        for k = 1:length(file)

            C{k,m} = A{k,1} - B{m,1};
            if C{k,m}<0
                C{k,m} = -C{k,m};
            end
        end
    end

    [V,X] = min(cell2mat(C),[],1); % Is a row vector containing the minimum value of columns
    % V gives minimum value and X gives Index

    m = 1;
    for w= X

        depthDataBase = file3(w).name;
        rgbDataBase = file4(m).name;

        depthData = fullfile(depth_img, depthDataBase);
        rgbData = fullfile(Openpose, rgbDataBase);

        imageArrayy = imread(depthData);
        imageArrayy2 = imread(rgbData);

        depthData2 = fullfile(selected_depth, depthDataBase);
        imwrite(imageArrayy, depthData2);
        rgbData2 = fullfile(selected_color, rgbDataBase);
        imwrite(imageArrayy2, rgbData2);

        m = m+1; % for part 2 m = m+1
    end

    %
    % PART 2:- If RGB images are more than depth then use the following code
else

    for m = 1:length(file2)
        for k = 1:length(file)

            C{m,k} = A{k,1} - B{m,1};
            if C{m,k}<0
                C{m,k} = -C{m,k};
            end
        end
    end

    [V,X] = min(cell2mat(C),[],1); % Is a row vector containing the minimum value of columns
    % V gives minimum value and X gives Index

    w = 1;
    for m= X

        depthDataBase = file3(w).name;
        rgbDataBase = file4(m).name;

        depthData = fullfile(depth_img, depthDataBase);
        rgbData = fullfile(Openpose, rgbDataBase);

        imageArrayy = imread(depthData);
        imageArrayy2 = imread(rgbData);

        depthData2 = fullfile(selected_depth, depthDataBase);
        imwrite(imageArrayy, depthData2);
        rgbData2 = fullfile(selected_color, rgbDataBase);
        imwrite(imageArrayy2, rgbData2);

        w = w+1;
    end
end

Update 1:- Screenshot of Profile execution time.


texts: Is this a good/safe way to convert enums?

texts:
Due to the fact that Entity does not support Enums, I am converting them to strings, string lists, and back again.

The reason is two fold:
type-safety, and consistency in the database.

Now, I have a bunch of these, but I will use Credit Cards as an example:

    public enum CreditCardName
    {
        VISA,
        Master_Card,
        Discover,
        American_Express
    }

Originally, I decided on writing the same method for them, over and over again:

    public static List<string> GetCreditCardTypes()
    {
        var list = Enum.GetNames(typeof(CreditCardName));
        return list.Select(n => n.Replace("_", " ")).ToList();
    }

Then it occurred to me that I could make one private method to do this:

    public static List<string> GetCreditCardTypes()
    {
        return EnumToList(typeof(CreditCardName));
    }

    private static List<string> EnumToList(Type type)
    {
        var list = Enum.GetNames(type);
        return list.Select(n => n.Replace("_", " ")).ToList();
    }

Now I'm also doing something similar in reverse, but will skip the code.  The question I have is if this is a good way to go about this?  I know there are other workarounds for Entity's lack of enum support, but they are a bit cumbersome for my simple needs.  I have never used Types in this way, so I just wanted to check that this is how Type/typeof are intended to be used, and that this will not cause unforeseen runtime issues.


texts:
Project Euler #6:

  The sum of the squares of the first ten natural numbers is,

  \$1^2+2^2+ ... + 10^2 = 385\$

  The square of the sum of the first ten natural numbers is,

  \$(1+2+ ... + 10)^2 = 55^2 = 3025\$

  Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is \$3025 − 385 = 2640\$.

  Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

Here is my solution:

public class DifferenceFinder {

    private static final int MAX = 100;

    public static void main(String[] args) {
        long time = System.nanoTime();
        int result = MAX * (MAX + 1) / 2;
        result *= result;
        for(int i = 1; i <= MAX; i++) {
            result -= i * i;
        }
        time = System.nanoTime() - time;
        System.out.println("Result: " + result
                + "\nTime used to calculate in nanoseconds: " + time);
    }

}

It simply does:

$$(1+2+ ... + 100)^2-1^2-2^2- ... -100^2$$

Output:

  Result: 25164150
Time used to calculate in nanoseconds: 2231

Questions:

Is the simplest solution the most efficient one?
Does it smell?


texts: Prime less than N that is a sum of the most consecutive other primes

texts:
Here's a Python implementation of the Sieve of Eratosthenes:

def return_primes(upto=100):
    primes = []
    sieve = set()
    for i in range(2, upto+1):
        if i not in sieve:
            primes.append(i)
            sieve.update(range(i, upto+1, i))
    return primes

I use the above function in the below algorithm to find the prime that is the sum of the most consecutive primes. I'm sure it has room for improvement. It starts with a small sliding window which iteratively increases in size, and each iteration goes until the found sum is greater than the largest prime, and then breaks to the outer iteration. Optimized for Python 2:

def find_prime_sum_of_most_consecutive_primes_under(x):
    '''
    given x, an integer, return the prime that is the sum
    of the greatest number of consecutive primes under x
    '''
    primes = return_primes(x)
    length = len(primes)
    primeset = set(primes)
    maxprime = primes[-1] # last prime
    result = None
    for window in xrange(1, length): # xrange should be range in Python 3
        iters = length - window
        for it in xrange(iters):
            s = sum(primes[it:window+it])
            if s in primeset:
                result = s
            if s > maxprime:
                break
    return result

Can this be improved?


texts: Implementing a date validator using enum

texts:
First and second post on the same subject. This is such a great way to learn.

Once again I'm open to suggestions. I have implemented almost all of the suggestions from before, which have resulted in the code looking like this:

import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

enum DateValidator {
    DDMMYYYY(0, 2, 4),
    MMDDYYYY(2, 0, 4),
    YYYYMMDD(6, 4, 0);

    private final int dayIndex;
    private final int monthIndex;
    private final int yearIndex;

    private DateValidator(int dayIndex, int monthIndex, int yearIndex) {
        this.dayIndex = dayIndex;
        this.monthIndex = monthIndex;
        this.yearIndex = yearIndex;
    }

    private int getDay(String date){ return Integer.parseInt(date.substring(dayIndex, dayIndex + 2)); }
    private int getMonth(String date){ return Integer.parseInt(date.substring(monthIndex, monthIndex + 2)); }
    private int getYear(String date){ return Integer.parseInt(date.substring(yearIndex, yearIndex + 4)); }

    private static boolean isLeapYear(int y) {
        return (y % 4 == 0) && ((y % 100 != 0) || (y % 400 == 0));  }

    private boolean isDateLegal(String date) {
        final int day = getDay(date);
        final int month = getMonth(date);
        final int year = getYear(date);
        boolean isValid = false;

        final Set<Integer> values = new HashSet<Integer>(Arrays.asList(1, 3, 5, 7, 8, 10, 12));
        final int daysInFebruary = (month == 2 && isLeapYear(year)) ? 29 : 28;

        if (day > 0) {
            if (values.contains(month)) { isValid = day <= 31; }
            else if (month > 0 && month < 13 && month != 2) { isValid = day <= 30; }
            else if (month == 2) isValid = day <= daysInFebruary;
        }

        return isValid;
    }

    private static boolean isDateFormatValid(String date) {

        final String DATE_PATTERN = "(^" + "[0-9]{2}\\.[0-9]{2}\\.[1-2][0-9]{3}|" +
                                     "[0-9]{2}\\-[0-9]{2}\\-[1-2][0-9]{3}|" +
                                     "[0-9]{2}\\/[0-9]{2}\\/[1-2][0-9]{3}|" +
                                     "[0-9]{2}\\s[0-9]{2}\\s[1-2][0-9]{3}|" +
                                     "[0-9]{2}[0-9]{2}[1-2][0-9]{3}|" +
                                     "[1-2][0-9]{3}\\.[0-9]{2}\\.[0-9]{2}|" +
                                     "[1-2][0-9]{3}\\-[0-9]{2}\\-[0-9]{2}|" +
                                     "[1-2][0-9]{3}\\/[0-9]{2}\\/[0-9]{2}" +
                                     "[1-2][0-9]{3}\\s[0-9]{2}\\s[0-9]{2}" +
                                     "[1-2][0-9]{3}[0-9]{2}[0-9]{2}" +")$";

        Pattern pattern = Pattern.compile(DATE_PATTERN);
        Matcher matcher = pattern.matcher(date);

        return matcher.matches();
    }

    public boolean validate(String date) {
        return this.isDateLegal(date.replaceAll("[\\.\\-\\/\\s]", "")) && isDateFormatValid(date);
    }
}

class Main {
    public static void main(String[] args) {
        System.out.print(DateValidator.DDMMYYYY.validate("16.10.1990") ? "Date is valid" : "Date is NOT valid");
    }
}


texts:
Detecting types in JavaScript sucks

This answer discusses the standard way to check the type of a JavaScript object (specifically, an array):

  The method given in the ECMAScript standard to find the class of
  Object is to use the toString method from Object.prototype.

if( Object.prototype.toString.call( someVar ) === '[object Array]' ) {
    alert( 'Array!' ); }

Why abuse Object.prototype.toString? It turns out that objects created in different frames have different constructors.

typeof only works for objects which are (or have equivalent) primitives, like strings.

Another way?

The above code makes me feel funny inside, and doesn’t have a chance of working for custom types, so I wrote this [Gist]:

function isType(object, type){
     return object != null && type ? object.constructor.name === type.name : object === type;
}

You use it like this:

isType([1, 2, 3], Array);
isType(null, null);
isType('foo', String);

mauke on ##javascript points out that it fails for objects whose constructors have the same name as the type you're testing against:

isType(new (function String(){}), String);

I think I like this behavior more than calling every custom type an Object.

To take it one step further

jQuery has a 25-line isPlainObject to tell if something is a plain object ({ foo: 'bar' }).

In what cases does the jQuery version behave more-correctly than…

isType(thing, Object);

?

Disclaimer: I haven’t tested this code in a bunch of cases or in a bunch of browsers. The experience concentrated into the jQuery source could blow me back to preschool.


texts: A "policy-based" design for a generic CUDA kernel

texts:
I am faced with a design issue that has been discussed on SO several times, the most similar question being this one.  Essentially, I want polymorphism for a CUDA kernel in the form of a "generic" kernel that can apply a "user-supplied" function to every element in an array.

In C++, one could achieve this design by using abstract base classes.  Here's a minimal example:

#include<iostream>
#include<vector>

class AbstractFunction{
    public:
        virtual double EvalFunction(double) const = 0;
        virtual std::vector<double> operator()(std::vector<double>) const;
};

std::vector<double> AbstractFunction::operator()(std::vector<double> x) const{
    std::vector<double> y;
    for(auto it=x.begin();it!=x.end();++it)
        y.push_back(EvalFunction(*it));
    return y;
}

class ConcreteFunction : public AbstractFunction{
    public:
        double EvalFunction(double x) const {return x*x;}
};

int main()
{
    ConcreteFunction f;
    std::vector<double> x(2,1);
    x[0] = 1.0; x[1] = 2.0;
    std::vector<double> y = f(x);
    for(auto it=y.begin();it!=y.end();++it)
        std::cout<<*it<<std::endl;

    return 0;
}

As it turns out, this design is nearly impossible to port to CUDA, because CUDA doesn't play nicely with abstract base classes.  Fine.  After some digging (this question and this question were very useful), I have come up with the following design, which seems to work quite well, but I'd like to hear some critiques:

#include<iostream>

// The Managed class allows us to use CUDA unified memory.
// See http://devblogs.nvidia.com/parallelforall/unified-memory-in-cuda-6/
class Managed {
public:
  void *operator new(size_t len) {
    void *ptr;
    cudaMallocManaged(&ptr, len);
    cudaDeviceSynchronize();
    return ptr;
  }
  void operator delete(void *ptr) {
    cudaDeviceSynchronize();
    cudaFree(ptr);
  }
};

// Evaluate function on GPU
template<class FunType>
__global__ void EvalKernelGPU(double* x,double* y,int N,FunType* f)
{
    unsigned int tId = blockIdx.x*blockDim.x + threadIdx.x;
    if(tId<N)
        y[tId] = (*f)(x[tId]);
}

//Evaluator class: "policy-based" template design
template<class FunType>
class Evaluator : public FunType
{
    public:
        Evaluator() {f = new FunType;}
        Evaluator(FunType* fun_in) {f = fun_in;}
        double* EvalFunGPU(double* x,int N){
            double* y;
            cudaMallocManaged(&y,N*sizeof(double));
            dim3 block(512,1);dim3 grid((N+block.x-1)/block.x,1);
            EvalKernelGPU<FunType><<<grid,block>>>(x,y,N,f);
            cudaDeviceSynchronize();
            return y;
        }
    private:
        FunType* f;
};
//"User-defined" special function, to be evaluated
struct SpecialFun : public Managed
{
    __device__ __host__ double operator()(double x){return x*x;}
};

int main()
{
    Evaluator<SpecialFun> E;
    double* x;
    cudaMallocManaged(&x,2*sizeof(double));
    x[0] = 1.0; x[1] = 2.0;
    double* y = E.EvalFunGPU(x,2);
    std::cout<<"y[0] = "<<y[0]<<"\ny[1] = "<<y[1]<<std::endl;

    return 0;
}

I have some obvious improvements lined up, but I wanted to get input on my basic design before building it out.  Thanks for your time!


texts: Make a perfect Split based on absolute difference between max of two arrays

texts:
I was solving this problem in Python3 on the Codechef website.  Here I've to split an array such that the absolute difference between the maximum of both the arrays is maximum.

For example, if the input array is [1, 3, -3] then it can be split in two ways:

Way-1:

[1] and [3,-3] --> Absolute difference between max of arrays is 3-1 = 2

Way-2:

[1,3] and [-3] --> Absolute difference between max of arrays is 3 - (-3) = 6

So the max difference is 6, which is the answer.

Below is my code:

def max_difference(a):
    max_diff = 0
    for i in range(len(a) -1):
        local_diff = abs(max(a[:i+1]) - max(a[i+1:]))
        if max_diff < local_diff:
            max_diff = local_diff
    return max_diff

if __name__ == '__main__':
    arr_count = int(input())
    arr = list(map(int, input().rstrip().split()))
    res = max_difference(arr)
    print(res)

Can you please tell me if this code fine?  What improvements can be done?


texts: Convert hex to base64 and then fixed XOR


texts:
I am learning MIPS as a part of my Computer Organization class at school and I am writing a simple program that reads in a positive integer from the user and tells the user whether the number is even or odd. The program works, but the way I had to split the loop and conditionals into different labels concerns me a little bit.

I could not figure out another way to do it, but as loops and conditionals are very common in code, I want to see if there is a way to do it without creating so many labels. If and when I tackle a bigger project in MIPS, I do not want to have to have 10 different loop labels if there is a better way to do it.

.data
        prompt: .asciiz "\nEnter a integer: "
        even_msg: .asciiz "\nThe number is even.\n"
        odd_msg: .asciiz "\nThe number is odd.\n"
        goodbye: .asciiz "\nGoodbye!\n"
.text

main:
        j loop

loop:
        la $a0, prompt
        li $v0, 4
        syscall

        # Read in value
        li $v0, 5
        syscall

        # If number is negative, exit program.
        slt $t0, $v0, $zero
        bne $t0, $zero, exit

        # Call even_or_odd on value
        add $a0, $v0, $zero
        jal even_or_odd
        j loop

even_or_odd:
        addi $t0, $zero, 2 # Set divisor to 2
        div $a0, $t0
        mfhi $t0           # Save remainder
        beq $t0, $zero, even
        j odd

even:
        la $a0, even_msg
        li $v0, 4
        syscall
        j return
odd:
        la $a0, odd_msg
        li $v0, 4
        syscall
        j return

return:
        lw $t0, 0($sp)
        addi $sp, $sp, 4
        jr $ra

exit:
        la $a0, goodbye
        li $v0, 4
        syscall

        li $v0, 10
        syscall