texts: Starting and stopping a thread for a command handler

texts:
I built an application class that should be runnable as a Thread and it would be nice to hear opinions of Java developers to improve my coding style.

Main class.

package com.ozankurt;

public class Main {

    public static void main(String[] args) {

        Application application = new Application();

        application.start();

    }
}

Application class:

package com.ozankurt;

import com.ozankurt.utilities.Input;

public class Application implements Runnable {

    private CommandHandler commandHandler;

    private boolean running;

    private volatile Thread thread;
    private String threadName = "ApplicationThread";

    public Application() {

        Handler handler = new Handler(this);

        this.commandHandler = new CommandHandler(handler);

        this.running = true;
    }

    public void start() {

        if (thread != null) {
            System.out.println(threadName + "is already running.");

            if (!isRunning())
            {
                System.out.println("Resuming " + threadName + "...");
                setRunning(true);
            }
        } else {
            System.out.println("Starting " + threadName + "...");

            thread = new Thread(this, threadName);
            thread.start();

            System.out.println("Started " + threadName + ".");
        }
    }

    public void stop() {
        System.out.println("Halting " + threadName + "...");

        setRunning(false);

        System.out.println("Halted " + threadName + ".");
    }

    @Override
    public void run() {

        while (isRunning()) {
            String userInput = Input.readLine();

            commandHandler.handle(userInput);
        }
    }

    public boolean isRunning() {

        return running;
    }

    public void setRunning(boolean running) {

        this.running = running;
    }
}

I read this Java documentation about how to stop threads in Java without using stop method that has become deprecated because it might throw some exceptions.

As far as I understand we shouldn't try to stop a thread and instead we should define a property corresponding to the state of the thread.

In my case I defined a boolean running in my Application class and as you can read from my code in the run method I basicly check if the application is running. Which mean that I actually never stop the thread, I only remove its functionality by using a while statement. Is this the correct approach explained in the Java documentation?


texts:
I have made a funtion to compare text files line by line, where timestamps and jobnumbers are replaced for a identical string. By lack of experience I'm not sure if this is the best way to do this.

if (row < comparedFile.Count)
{
    var regexJobNumber = @"([0-9]{4})";
    var regexTimeStamp = @"([0-9]{8}_[0-9]{6})";
    var input = line;
    var removeTimestamp = Regex.Matches(input, regexTimeStamp).Cast<object>().Aggregate(input, (current, Match) => Regex.Replace(current, regexTimeStamp, "<TimeStamp>"));
    var removeJobnumber = Regex.Matches(removeTimestamp, regexJobNumber).Cast<object>().Aggregate(removeTimestamp, (current, Match) => Regex.Replace(current, regexJobNumber, "<JobNummer>"));

    var input2 = comparedFile[row];
    var removeTimestamp2 = Regex.Matches(input2, regexTimeStamp).Cast<object>().Aggregate(input2, (current, Match) => Regex.Replace(current, regexTimeStamp, "<TimeStamp>"));
    var removeJobnumber2 = Regex.Matches(removeTimestamp2, regexJobNumber).Cast<object>().Aggregate(removeTimestamp2, (current, Match) => Regex.Replace(current, regexJobNumber, "<JobNummer>"));

    if (!removeJobnumber.Equals(removeJobnumber2))
    {
       var rowcount = row + 1;
       differenceList.Add("Difference found on rownumber: " + rowcount);
    }
    row++;
}


texts:
How would you DRY up this RSpec code?

require "spec_helper"

describe InvoiceMailer do
  let(:user) { create(:user) }
  let(:student) { create(:student, user: user) }
  let(:body) { "And I for one will join with anyone, don't care what color you are. As long as you want change this miserable condition that exists on this earth." }
  subject(:mail) { InvoiceMailer.issue(student, body) }

  describe "issue" do
    subject(:mail) { InvoiceMailer.issue(student, body) }

    it "renders the subject" do
      expect(mail.subject).to eq "New Invoice!"
    end

    it "renders the receiver email" do
      expect(mail.to).to eq [student.user.email]
    end

    it "renders the sender email" do
      expect(mail.from).to eq ["info@test.com"]
    end
  end

  describe "rescind" do
    subject(:mail) { InvoiceMailer.rescind(student, body) }

    it "renders the subject" do
      expect(mail.subject).to eq "Invoice Rescinded!"
    end

    it "renders the receiver email" do
      expect(mail.to).to eq [student.user.email]
    end

    it "renders the sender email" do
      expect(mail.from).to eq ["info@test.com"]
    end
  end

end


texts: Simplify my class mapping common class properties between model and viewmodel classes

texts:
I have an ASP.NET MVC 5 app and I map properties between model and viewmodel and vice versa.

I could use automapper to do this but since I don't need mapping rules to convince me to use it as I mostly do simple 1 to 1 mapping the  performance overhead that automapper will add is not worthwhile.If I have mapping differences I'll map it manually where I reference it in my controller.

Here is my code

public class Dog
{
    public int Id { get; set; }

    public string Name { get; set; }

    public DateTime? BirthDate { get; set; }

    public int? CreatedBy{ get; set; }

    public DateTime? DateCreated { get; set; }
}

public class DogViewModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public DateTime? BirthDate { get; set; }

    public static implicit operator DogViewModel(Dog dm)
    {
        var vm= new DogViewModel{
            Id = dm.Id,
            Name = dm.Name,
            BirthDate = dm.BirthDate
       };
        return vm;
    }

    public static implicit operator Dog(DogViewModel vm)
    {
        var dm = new Dog
        {
            Id = vm.Id,
            Name = vm.Name,
            BirthDate = vm.BirthDate
        };
        return dm;
    }
}

This allows me to in my controller actionmethods easily map one class to another.

e.g.

  public async Task<IActionResult> Edit(int? id)
    {
        var dog= await _db.Dogs.FirstOrDefaultAsync(d => md.Id == id);
        DogViewModel dogVm = dog;
        ...

     }

    [HttpPost]
    public async Task<IActionResult> Edit(DogViewModel dogVm)
    {
       Dog dog= dogVm;
       ...
    }

In my index ActionMethod I need to map a list of items.

  public async  Task<IActionResult> Index()
    {
        var dogs = await _db.Dogs.ToListAsync();

        var dogVms = new List<DogViewModel>();
        foreach (var dog in dogs)
        {
            DogViewModel dogVm = dog;
            dogVms.Add(dogVm);
        }
        return View(dogVms);
    }

Question: Is there a way in LINQ or some other way in C# to eliminate the above foreach clause to simplify this code?


texts:
I needed to convert a formatted file size back into its length in bytes. I came up with the following code but want it reviewed:

/**
 * Converts a formatted size to its equivalent in bytes.
 *
 * @param size
 *            The formatted file size. Examples: "125.5 MB", "1KiB", "0.8 GB"
 * @return
 * @throws NumberFormatException
 */
public static long getBytesFromFormattedSize(final String size) throws NumberFormatException {
    final String[] arr = size.toUpperCase().split(" ");
    if (arr.length != 2) {
        if (arr.length == 1 && Character.isDigit(size.charAt(0))) {
            // Treat this as a formatted size missing the space.
            return getBytesFromSize(size);
        }
        throw new IllegalArgumentException("Expected '<size> <unit>', got '" + size + "'");
    }
    final char unit = arr[1].charAt(0);
    if (unit == 'B') {
        return Integer.parseInt(arr[0]);
    }
    final int bytes = arr[1].length() == 3 && arr[1].charAt(1) == 'I' ? 1000 : 1024;
    final char[] units = {
            'K', 'M', 'G', 'T', 'P', 'E'
    };
    int exp = 1;
    for (final char ch : units) {
        if (unit == ch) {
            break;
        }
        exp++;
    }
    return (long) (Double.parseDouble(arr[0]) * Math.pow(bytes, exp));
}

private static long getBytesFromSize(final String size) {
    String fixedSize = "";
    for (final char c : size.toCharArray()) {
        if (Character.isLetter(c) && !fixedSize.contains(" ")) {
            fixedSize += ' ';
        }
        fixedSize += c;
    }
    return getBytesFromFormattedSize(fixedSize);
}

Some tests:

String[] sizes = {
        "1 KB", "100 MB", "100MiB", "1 GB", "100B", "1.5 MB"
};
for (String size : sizes) {
    System.out.println(String.format("%s = %d bytes", size, getBytesFromFormattedSize(size)));
}

Output:

1 KB = 1024 bytes
100 MB = 104857600 bytes
100MiB = 100000000 bytes
1 GB = 1073741824 bytes
100B = 100 bytes
1.5 MB = 1572864 bytes


texts:
So its my first time using Kotlin, and for now I am converting old Java code to Kotlin. I took a simple function to parse a JSONArray from a JSONobject with a key. Here is the code:

fun getJSONArrayFromObject(jsonObject: JSONObject, key: String): JSONArray {
    var array = jsonObject.optJSONArray(key)

    if (array == null) {
        array = JSONArray()

        val tmp = jsonObject.optJSONObject(key)

        if (tmp != null)
            array.put(tmp)
    }

    return array
}

Is this idiomatic Kotlin, syntax-wise?

One more thing, since input parameters are final, am I supposed to convert them into a dummy object, like a copy object? I'm currently handling that as follows:

fun parse(data: MyData?, myObject: JSONObject) : MyData {
    var dataCopy = data

    if (dataCopy == null)
        dataCopy = MyData()

    if(myObject.optJSONObject("testing") != null) {
        val mySecondJson = myObject.optJSONObject("pc")

        if(mySecondJson.optJSONObject("testingSecond") != null) {
            val myJson = mySecondJson.optJSONObject("myJson")

            val myDataParser = MyDataParser()

            data?.myDataList = myDataParser.parse(myJson)
        } else {
            debug { "Missing" }
        }
    } else {
        debug { "Missing"}
    }

    return dataCopy
}


texts:
Objective

To create a unique id with few characters as possible.

Language: C#
Engine Unity3D
Target : iOS && iPadOS

Scenario

I found quite a few solutions from Stack Exchange but would like to know if someone could just look at my code to review it. It is a very important module IMO

Code

    /// <summary>
    /// Identifiers the generation.
    /// </summary>
    /// <returns>A Unique ID</returns>
    private string generateUniqueID(int _characterLength = 11)
    {
        StringBuilder _builder = new StringBuilder();
        Enumerable
            .Range(65, 26)
            .Select(e => ((char)e).ToString())
            .Concat(Enumerable.Range(97, 26).Select(e => ((char)e).ToString()))
            .Concat(Enumerable.Range(0, 10).Select(e => e.ToString()))
            .OrderBy(e => Guid.NewGuid())
            .Take(_characterLength)
            .ToList().ForEach(e => _builder.Append(e));
        return _builder.ToString();
    }

In the above code, I always pass _characterLength to be always 11.

Request

Would you recommend the above method? If not, could you please specify why?


texts:
I have coded a script that I run when I need to verify the authentication for a user, I use it as a php script and host it on api.mydomain.com. It just simply checks to see if the user details are correct, the same as the parameters passed and to check if the account has a subscription.

The end result is checking if the response contains congratulations.

<?php
$connection = mysqli_connect(
    "localhost",
    "root",
    "",
    "mydb"
);

if (mysqli_connect_errno()) {
    exit('failed to connect to the database server.');
}

if (!isset($_GET['auth_username']) || !isset($_GET['auth_password'])) {
    exit('you failed to provide the correct parameters.');
}

$username = isset($_GET['auth_username']) ? $_GET['auth_username'] : '';
$password = isset($_GET['auth_password']) ? $_GET['auth_password'] : '';

$commandText = "SELECT `password`,`has_subscription` FROM `a__client_accounts`";
$whereClause = "WHERE `username` = '" . $username . "'";
$result = $connection->query($commandText . " " . $whereClause);

if (!$result) {
    exit('Invalid query: ' . $connection->error);
}
else if ($result->num_rows > 0) {
    $array =  $result->fetch_array();

    if (!password_verify($password, $array['password'])) {
        exit('we found your account, but you entered the wrong password.');
    }
    else if ($array['has_subscription'] == '0') {
        exit('you authenticated, but you don\'t have a subscription');
    }
    else {
        exit('congratulations');
    }
}
else {
    echo 'no account was found with that name.';
}


texts: Abstract factory or inversion of control pattern?

texts:
I have several generic methods that use the typeof operator to determine the type of mapper class to create.  Eventually this is going to get out of hand.

Can anyone suggest a better way to handle this?  I have been reading up a bit and it seems like an abstract factory pattern or IOC would be a good pattern to use.  I'm not familiar with IOC.  Can someone provide an opinion on which would be better in this scenario?

internal UpdateStudentDocumentRequest MapDocToUpdateDocumentRequest<T>(T doc)
{
    Type docType = typeof(T);

    //V1
    if
    (
        docType == typeof(IndV1201314Model) ||
        docType == typeof(IndV1201415Model) ||
        docType == typeof(DepV1201415Model)
    )
    { return new V1DocMapper<Models.Verification.V1Base>().MapV1ToUpdateStudentDocumentRequest(doc as Models.Verification.V1Base); }

    //V3
    if
    (
        docType == typeof(IndV3201314Model) ||
        docType == typeof(IndV3201415Model) ||
        docType == typeof(DepV3201415Model)
    )
    { return new V3DocMapper<Models.Verification.V3Base>().MapV3ToUpdateStudentDocumentRequest(doc as Models.Verification.V3Base); }

    //FASchol
    if (docType == typeof(FAScholModel))
    {return new FAScholMapper().MapFAScholToUpdateStudentDocumentRequest(doc as FAScholModel);}

    return new UpdateStudentDocumentRequest();
}


texts: Long expression to sum data in a multi-dimensional model

texts:
I am porting a linear optimization model for power plants from GAMS to Pyomo. Models in both frameworks are a collection of sets (both elementary or tuple sets), parameters (fixed values, defined over sets), variables (unknowns, defined over sets, value to be determined by optimization) and equations (defining relationships between variables and parameters).

In the following example, I am asking for ideas on how to make the following inequality more readable:

def res_stock_total_rule(m, co, co_type):
    if co in m.co_stock:
        return sum(m.e_pro_in[(tm,)+ p] for tm in m.tm for p in m.pro_tuples if p[1] == co) + \
               sum(m.e_pro_out[(tm,)+ p] for tm in m.tm for p in m.pro_tuples if p[2] == co) + \
               sum(m.e_sto_out[(tm,)+ s] for tm in m.tm for s in m.sto_tuples if s[1] == co) - \
               sum(m.e_sto_in[(tm,)+ s] for tm in m.tm for s in m.sto_tuples if s[1] == co) <= \
               m.commodity.loc[co, co_type]['max']
    else:
        return Constraint.Skip

Context:

m is a model object, which contains all of the above elements (sets, params, variables, equations) as attributes.
m.e_pro_in for example is a 4-dimensional variable defined over the tuple set (time, process name, input commodity, output commodity).
m.tm is a set of timesteps t = {1, 2, ...}, m.co_stock the set of stock commodity, for which this rule will apply only (otherwise, no Constraint is generated via Skip).
m.pro_tuples is a set of all valid (i.e. realisable) tuples (process name, input commodity, output commodity).
m.commodity is a Pandas DataFrame that effectively acts as a model parameter.

My question now is this:

Can you give me some hints on how to improve the readability of this fragment? The combination of tuple concatenation, two nested list comprehensions with conditional clause, Pandas DataFrame indexing, and a multiline expression with line breaks all make it less than easy to read for someone who might just be learning Python while using this model.


texts:
Consider this interview question:

  Given a Node with a reference to a child, its next, its previous, and a variable for its value (\$\frac{1}{2}\$ tree, \$\frac{1}{2}\$ doubly linked list structure), you have to find a way to flatten the structure.

1 = 2 = 3 = 5
    |       |
    6 = 7   8
        |
        9

  (reference down is child and reference across is next)

  this above diagram becomes: 1 - 2 - 6 - 7- 9 - 3 - 5 - 8 but:

  2 still has child reference to 6
  7 still has child reference to 9
  5 still has child reference to 8

Here is my code:

class Node(object):
    def __init__(self, value, next_node=None, prev=None, child=None):
        self.value = value
        self.next = next_node
        self.prev = prev
        self.child = child

    def __repr__(self):
        return str(self.value)

one = Node(1)
two = Node(2)
three = Node(3)
five = Node(5)
six = Node(6)
seven = Node(7)
eight = Node(8)
nine = Node(9)
one.next = two
two.prev = one
two.next = three
two.child = six
three.prev = two
three.next = five
five.prev = three
five.child = eight
six.next = seven
seven.prev = six
seven.child = nine

def flatten(head):
    if not head: return head

    c = flatten(head.child)
    n = flatten(head.next)
    if c:
        head.next = head.child
        head.child.prev = head
    if c and n:
        tail = c
        while tail.next:
            tail = tail.next
        tail.next = n
        n.prev = tail
    return head

n = flatten(one)
while n:
    print "%d -" % (n.value,),
    n = n.next

I don't like the while loop. I could store tail and pass it around. Any better solution?


texts:
I wonder if there could be a faster palindrome checker in Java. The best one I have is O(n/2) which is O(n) eventually:

  public static boolean isPalindromeNaive(String s) {
        StringBuilder sb = new StringBuilder(s);
        StringBuilder sbReverse = sb.reverse();

        if (s.equals(String.valueOf(sbReverse))){
            return true;
        }
        return false;
    }

    public static boolean isPalindromLessNaive(String s) {
        if (s.length()%2==0) {
            for (int i = 0; i<(s.length()/2); i++) {
                if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {
                    return false;
                }
            }
        }
        else {

            for (int i=0; i<(s.length()/2); i++) {
                if (s.charAt(i)!=s.charAt(s.length()-1-i)) {
                    return false;
                }

            }

        }

        return true;
    }

Also am I correct that my naive method is slower than less naive method? what is the time complexity of StringBuilder reverse() method?
// suggestion for code design/pattern(s) are really welcomed!


texts: Is it bad practice to increment more than one variable in a for loop declaration?

texts:
While coding today, I came across the following loop in C#:

for(int x = 0; x < max_x_index; x++){
    for(int y = 0; y < max_y_index; y++, count++){
        some2DarrayRepresentedBy1D[count] = ...;
    }
}

Would this be consider bad practice?  Would the following be a better way to achieve the same result:

for(int x = 0; x < max_x_index; x++){
    for(int y = 0; y < max_y_index; y++){
        some2DarrayRepresentedBy1D[count] = ...;
        count++;
    }
}

Would you allow both through, for example, a code review or would you tag the first example for being obscure?


texts: Append a note to one of three files based on user choice

texts:
The user selects one of the three categories then makes a note on that selection. Then the note is appended and saved to the appropriate list.

It took me four hours to write this. I'm trying to learn and was wondering if this could be improved or cleaned up at all.

#!/bin/bash

#get the date
date=$(date +%d-%B-%Y)

#save locations
wsave="${HOME}/worknotes.txt"
shsave="${HOME}/shoppingnotes.txt"
scsave="${HOME}/schoolnotes.txt"

#list
while [ true ]
do
read -p "What is this note for?
Work
School
Shopping
> " topic
case $topic in

    "Work" )
        read -p "
Note
> " wnote
        echo "$date: $wnote" >> "$wsave"
        echo "Note saved to $wsave"
            break
            ;;
    "Shopping" )
        read -p "
Note
> " shnote
        echo "$date: $shnote" >> "$shsave"
        echo "Note saved to $shsave"
            break
            ;;
    "School" )
        read -p "
Note
> " scnote
        echo "$date: $scnote" >> "$scsave"
        echo "Note saved to $scsave"
            break
            ;;
    *) echo "Error: Selection was not on list, try again.
"
            ;;
esac
done


texts:
I have this module which computes checksums from a list of files in a given directory.
The problem is that my is_changed_file is long and ugly, but my attempts in refactoring failed, so I would like some other point of views...

import hashlib
import logging

# if available use the faster cPickle module
try:
    import cPickle as pickle
except ImportError:
    import pickle

from os import path

class DirectoryChecksum(object):
    """Manage the checksums of the given files in a directory
    """

    def __init__(self, directory, to_hash):
        self.directory = directory
        self.to_hash = to_hash
        self.checksum_file = path.join(self.directory, '.checksums')
        self.checks = self._compute()
        self.logger = logging.getLogger("checksum(%s): " % self.directory)

    def _abs_path(self, filename):
        return path.join(self.directory, filename)

    def _get_checksum(self, filename):
        content = open(self._abs_path(filename)).read()
        return hashlib.md5(content).hexdigest()

    def _compute(self):
        """Compute all the checksums for the files to hash
        """
        dic = {}
        for f in self.to_hash:
            if self._file_exists(f):
                dic[f] = self._get_checksum(f)
        return dic

    def _file_exists(self, filename):
        return path.isfile(self._abs_path(filename))

    def is_changed(self):
        """True if any of the files to hash has been changed
        """
        return any(self.is_file_changed(x) for x in self.to_hash)

    #FIXME: refactor this mess, there is also a bug which impacts on
    #the airbus. eggs, so probably something to do with the path
    def is_file_changed(self, filename):
        """Return true if the given file was changed
        """
        if not self._has_checksum():
            self.logger.debug("no checksum is available yet, creating it")
            self.write_checksums()
            return True

        stored_checks = self.load_checksums()

        if not self._file_exists(filename):
            if filename in stored_checks:
                self.logger.debug("file %s has been removed" % filename)
                # what if it existed before and now it doesn't??
                return True
            else:
                return False

        checksum = self._get_checksum(filename)
        if filename in stored_checks:
            # if the file is already there but the values are changed
            # then we also need to rewrite the stored checksums
            if stored_checks[filename] != checksum:
                self.write_checksums()
                return True
            else:
                return False
        else:
            # this means that there is a new file to hash, just do it again
            self.write_checksums()
            return True

    def _has_checksum(self):
        return path.isfile(self.checksum_file)

    def load_checksums(self):
        """Load the checksum file, returning the dictionary stored
        """
        return pickle.load(open(self.checksum_file))

    def write_checksums(self):
        """Write to output (potentially overwriting) the computed checksum dictionary
        """
        self.logger.debug("writing the checksums to %s" % self.checksum_file)
        return pickle.dump(self.checks, open(self.checksum_file, 'w'))


texts: Marking loans as paid if the payments exceed the loan amount

texts:
I have a Rails app where Loan has paid attribute. Loan should be marked as paid if total sum of payments is equal or higher than loan amount_to_pay. Problem is that it is obligatory to have paid attribute and not checking it dynamically by joining payments to loans and selecting whether it is paid or not (long story...). So I have several options.

Option 1

Creating payments via Loan class. It helps to wrap it into transaction to be sure, that create and update would be executed. But as I understand I'm breaking single-responsibility principle here and loan have to worry about payment creation.

class Loan
  has_many :payments

  def pay!(payment_params)
    transaction do
      payments.create(payment_params)
      update(paid: true) if payments.total >= amount_to_pay
    end
  end
end

class Payment
  belongs_to :loan

  def self.total
    pluck(:amount).reduce(:+)
  end
end

loan = Loan.create(amount_to_pay: 1000)
loan.pay!({ amount: 500 })
loan.pay!({ amount: 500 })
loan.paid? #=> true

Option 2

Payments here are created directly, but there is no 100% guarantee that after_create will be executed. More over callbacks are difficult to test.

class Loan
  has_many :payments
end

class Payment
  belongs_to :loan

  after_create :mark_loan_as_paid

  def mark_loan_as_paid
    if loan.payments.total >= loan.amount_to_pay
      loan.update(paid: true)
    end
  end
end

loan = Loan.create(amount_to_pay: 1000)
Payment.create(amount: 500, loan_id: loan.id)
Payment.create(amount: 500, loan_id: loan.id)
loan.paid? #=> true

So, what is the best option to handle such cases (when some action in one class should change something in another).


texts: Refactor java methods that do not have a common hierarchy but have same API

texts:
I have this piece of code where the class ExecutionMessage has three variants. The point is that the classes are autogenerated by Apache CXF and they do not have a common class. But all the three flavors have the same API. Is there a way to refactor the same using generics or Java 8 semantics to avoid the repetition of code.

public void convertToList (ExecutionMessageV2 mesg, List<ErrorDetail> errors) {
    if (mesg == null) {
        return;
    }
    ErrorDetail err = new ErrorDetail(mesg.getCode(),mesg.getDescription(), mesg.getSourceExceptionName());
    if (mesg.getSeverity() != null)
        err.setSeverity(mesg.getSeverity().value());
    if (mesg.getType() != null)
        err.setType(mesg.getType().value());
    errors.add(err);
    convertToList(mesg.getDetail(), errors);
}

public void convertToList (ExecutionMessageV1_0 mesg, List<ErrorDetail> errors) {
    if (mesg == null) {
        return;
    }
    ErrorDetail err = new ErrorDetail(mesg.getCode(),mesg.getDescription(), mesg.getSourceExceptionName());
    if (mesg.getSeverity() != null)
        err.setSeverity(mesg.getSeverity().value());
    if (mesg.getType() != null)
        err.setType(mesg.getType().value());
    errors.add(err);
    convertToList(mesg.getDetail(), errors);
}

public void convertToList (ExecutionMessageV2_0 mesg, List<ErrorDetail> errors) {
    if (mesg == null) {
        return;
    }
    ErrorDetail err = new ErrorDetail(mesg.getCode(),mesg.getDescription(), mesg.getSourceExceptionName());
    if (mesg.getSeverity() != null)
        err.setSeverity(mesg.getSeverity().value());
    if (mesg.getType() != null)
        err.setType(mesg.getType().value());
    errors.add(err);
    convertToList(mesg.getDetail(), errors);
}


texts: Positive integer to Roman Numeral conversion function

texts:
For the past two hours I was searching for a built-in function for converting an integer to an equivalent Roman numeral, but it failed to achieve  the target. Hence I wrote my own routine for performing this conversion. I think it needs some more clarifications.

Public Class Form1
    Dim ind() As Integer = {1, 2, 3, 4, 5, 10, 50, 100, 500, 1000}
    Dim rom() As String = {"I", "II", "III", "IV", "V", "X", "L", "C", "D", "M"}
    Dim limit As Integer = 9
    Dim output As String = ""
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim num As Integer
        output = ""
        num = CInt(txt1.Text)
        While num > 0
            num = find(num)
        End While
        txt2.Text = output
    End Sub
    Public Function find(ByVal Num As Integer) As Integer
        Dim i As Integer = 0
        While ind(i) <= Num
            i += 1
        End While
        If i <> 0 Then
            limit = i - 1
        Else
            limit = 0
        End If
        output = output & rom(limit)
        Num = Num - ind(limit)
        Return Num
    End Function
End Class

Note:  This function can only be used for range of 1-999


texts: Unit-testing authorization policies in Rails with RSpec

texts:
The following specs test the authorization setup of the Post resource in a Rails 4.2 application. The Pundit gem is used for authorization but I believe the specs be easily adapted to work with most role-based authorization setups. The code was inspired by this blog post.

The User model has_many :posts and the Post model belongs_to :user.

The code works as expected but it would be great to receive feedback and suggestions from more experienced developers.

Custom Matcher

RSpec::Matchers.define :permit do |action|
  match do |policy|
    policy.public_send("#{action}?")
  end

  failure_message do |policy|
    "#{policy.class} does not permit #{action} on #{policy.record} for #{policy.user.inspect}."
  end

  failure_message_when_negated do |policy|
    "#{policy.class} does not forbid #{action} on #{policy.record} for #{policy.user.inspect}."
  end
end

Specs

require 'rails_helper'
require 'support/pundit_matcher'

describe PostPolicy do
  describe 'scope' do
    # The following "let" and "subject" blocks use variables defined within
    # other "let" blocks (user and scope). That's possible due to lazy loading.
    subject(:policy_scope) { PostPolicy::Scope.new(user,Post.all).resolve }
    let(:associated_post) { FactoryGirl.create(:post, user: user) }
    let!(:unassociated_post) { FactoryGirl.create(:post, user: nil) }

    context "for an unauthenticated user" do
      let(:user) { nil }
      it "hides all posts" do
        # unassociated_post is eagerly created so it exists within this test.
        expect(policy_scope).to eq nil
      end
    end

    context "for an ordinary user" do
      let(:user) { FactoryGirl.create(:user) }
      it "only shows posts associated with the user" do
        expect(policy_scope).to eq [associated_post]
      end
    end

    context "for an admin user" do
      let(:user) { FactoryGirl.create(:admin_user) }
      it "shows unpublished post" do
        expect(policy_scope).to include(associated_post, unassociated_post)
      end
    end
  end

  describe 'policy' do
    subject { PostPolicy.new(user, post) }
    let(:post) { FactoryGirl.create(:post, user: nil) }

    context "for an unauthenticated user" do
      let(:user) { nil }

      it { is_expected.to permit(:show) }
      it { is_expected.not_to permit(:create) }
      it { is_expected.not_to permit(:new) }
      it { is_expected.not_to permit(:update) }
      it { is_expected.not_to permit(:edit) }
      it { is_expected.not_to permit(:destroy) }
    end

    context "for an ordinary user" do
      let(:user) { FactoryGirl.create(:user) }

      it { is_expected.to permit(:create) }
      it { is_expected.to permit(:new) }

      context "and a post that is NOT associated to that user" do
        it { is_expected.to permit(:show) }
        it { is_expected.not_to permit(:update) }
        it { is_expected.not_to permit(:edit) }
        it { is_expected.not_to permit(:destroy) }
      end

      context "and a post that IS associated to that user" do
        let(:post) { FactoryGirl.create(:post, user: user) }

        it { is_expected.to permit(:show) }
        it { is_expected.to permit(:update) }
        it { is_expected.to permit(:edit) }
        it { is_expected.to permit(:destroy) }
      end
    end

    context "for an admin" do
      let(:user) { FactoryGirl.create(:admin_user) }

      it { is_expected.to permit(:show) }
      it { is_expected.to permit(:create) }
      it { is_expected.to permit(:new) }
      it { is_expected.to permit(:update) }
      it { is_expected.to permit(:edit) }
      it { is_expected.to permit(:destroy) }
    end
  end
end


texts: Sorting numeric  tags without omitting the attributes

texts:
I used the following Javascript to sort an unnumbered list of numeric li-tags as follows:

// 1. get the
-element from the BODY
var nList = document.getElementById("allItems");
// 2. extract all the
-elements from that
 and put it in a NodeList
var nEntry = nList.getElementsByTagName('li');

// 3. we can't sort a NodeList, so first make it an Array
var nEntryArray = Array.prototype.slice.call(nEntry, 0);

// 4. sort the array, the normal sort()-function won't do because it is an alphabetical sort
// to sort() numeric values, see http://www.w3schools.com/jsref/jsref_sort.asp example, as "Default sort order is alphabetic and ascending. When numbers are sorted alphabetically, "40" comes before "5".  To perform a numeric sort, you must pass a function as an argument when calling the sort method."
// the numeric value of the
 nodes can be located in nEntryArray[i].firstChild.nodeValue , so compare those

nEntryArray.sort(function(a,b){
  return a.firstChild.nodeValue - b.firstChild.nodeValue
})

// 5. empty the nList and refill it with those in the correct order at the nEntryArray
while (nList.lastChild)
{
  nList.removeChild(nList.lastChild);
}

for (i=0; i<nEntryArray.length; i++)
{
  nList.appendChild(nEntryArray[i]);
}

If a HTML-code is given with a list as such:

100

10

1

20

16

it will order the list numerically without omitting the attributes of the
-tags.

It is one of my first JavaScript-attempts, and I was wondering if this is indeed correct or whether it could be simplified. Especially the conversion from Nodelist to Array seems redundant to me, but I haven't found a more gracious solution.

I post this code-block as I was looking on StackOverflow and through Google for a piece of code to help me solve this particular problem, but I couldn't find something that was understandable to a beginner like me. I easily found ways to sort lists , but then the attributes would be omitted and in the end it took me two days (yep, beginner :-)) to come up with this solution.

Any comments?


texts:
I had a challenge a while back from a friend to try and produce the fastest possible program to compute A(3,16), where A is the Ackermann function.

He wrote it in Java, and it took ~4.4 seconds. The below (very ugly) Haskell program that I wrote took ~1.7 seconds:

{-# LANGUAGE BangPatterns #-}

import           Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map

-- Main method:

main :: IO ()
main = print $ fst $ ack (I 3 16) Map.empty

-- Definitions:

data I = I {-# UNPACK #-} !Int {-# UNPACK #-} !Int
    deriving (Eq, Ord)

ack :: I -> Map I Int -> (Int, Map I Int)
ack   (I 0 n) r  = (n + 1, r)

ack i@(I m 0) r1 = maybe bak fun (Map.lookup i r1)
    where
        (!val, !r2) = ack (I (m-1) 1) r1
        bak       = (val, Map.insert i val r2)
        fun v     = (v, r1)

ack i@(I m n) r1 = maybe bak2 fun2 (Map.lookup call2 r2)
    where
        call1       = (I m (n - 1))
        (!val1, !re1) = ack call1 r1
        bak1        = (val1, Map.insert call1 val1 re1)
        fun1 v      = (v, r1)
        (!v1, !r2)    = maybe bak1 fun1 (Map.lookup call1 r1)
        call2       = (I (m - 1) v1)
        (!val2, !re2) = ack call2 r2
        bak2        = (val2, Map.insert call2 val2 re2)
        fun2 v      = (v, r2)

This is used on Ints specifically because A(3,16) is 524285, which within Ints range.

How can I make this function more memory efficient, and faster for greater Ackermann calls?

Also, the syntax is disgusting. How can I make this more readable (maybe using monads?) without having horrible performance consequences?


texts:
I have Dijkstra's algorithm:

# ==========================================================================
# We will create a dictionary to represent the graph
# =============================================================================
graph = {
    'a' : {'b':3,'c':4, 'd':7},
    'b' : {'c':1,'f':5},
    'c' : {'f':6,'d':2},
    'd' : {'e':3, 'g':6},
    'e' : {'g':3, 'h':4},
    'f' : {'e':1, 'h':8},
    'g' : {'h':2},
    'h' : {'g':2}
}

def dijkstra(graph, start, goal):
    shortest_distance = {}     # dictionary to record the cost to reach to node. We will constantly update this dictionary as we move along the graph.
    track_predecessor = {}     # dictionary to keep track of path that led to that node.
    unseenNodes = graph.copy() # to iterate through all nodes
    infinity = 99999999999     # infinity can be considered a very large number
    track_path = []            # dictionary to record as we trace back our journey

    # Initially we want to assign 0 as the cost to reach to source node and infinity as cost to all other nodes
    for node in unseenNodes:
        shortest_distance[node] = infinity
    shortest_distance[start] = 0

    # The loop will keep running until we have entirely exhausted the graph, until we have seen all the nodes
    # To iterate through the graph, we need to determine the min_distance_node every time.
    while unseenNodes:
        min_distance_node = None
        for node in unseenNodes:
            if min_distance_node is None:
                min_distance_node = node
            elif shortest_distance[node] < shortest_distance[min_distance_node]:
                min_distance_node = node

        # From the minimum node, what are our possible paths
        path_options = graph[min_distance_node].items()

        # We have to calculate the cost each time for each path we take and only update it if it is lower than the existing cost
        for child_node, weight in path_options:
            if weight + shortest_distance[min_distance_node] < shortest_distance[child_node]:
                shortest_distance[child_node] = weight + shortest_distance[min_distance_node]
                track_predecessor[child_node] = min_distance_node

        # We want to pop out the nodes that we have just visited so that we dont iterate over them again.
        unseenNodes.pop(min_distance_node)

    # Once we have reached the destination node, we want trace back our path and calculate the total accumulated cost.
    currentNode = goal
    while currentNode != start:
        try:
            track_path.insert(0, currentNode)
            currentNode = track_predecessor[currentNode]
        except KeyError:
            print('Path not reachable')
            break
    track_path.insert(0, start)

    #  If the cost is infinity, the node had not been reached.
    if shortest_distance[goal] != infinity:
        print('Shortest distance is ' + str(shortest_distance[goal]))
        print('And the path is ' + str(track_path))

It works fine if I have a small amount of nodes (like in the code), but I have graph with around 480 000 nodes and by my approximation, in such a large graph, it will take 7.5 hours, and that is only 1 way! How could I make it work faster? In OSM, for instance it calculates in seconds!


texts: Reconstructing Matrix scattered over many MPI ranks

texts:
I have a program that does some matrix computations using MPI (MPICH). Each rank has a slice of the matrix and does the computations on their slice to get a new slice of the matrix. Sometimes I need to synchronize the matrix on the manager for snapshotting, output, etc. so I need all ranks to send their current matrix slice back to the manager.

I've come up with a solution to do this, and it seems to work OK; but I wanted to know whether this is a good approach or if I'm doing something stupid since I've never worked with MPI before. One thing I'm particularly curious about is whether I'm deleting my requests vector correctly. Thanks in advance!

Here's the code:

#define __WORLD MPI_COMM_WORLD

// reconstructs the matrix on the manager node
void reconstructMatrix(double** current, const int COLS, const int ROWS,
                       const int MY_RANK, const int MPI_SIZE)
{
    auto requests = new std::vector<MPI_Request*>();
    requests->reserve(COLS);

    // Manager receives data from all ranks
    if (MY_RANK == 0)
    {
        // number of columns assigned to all ranks
        const auto SLICE_SIZE = COLS / MPI_SIZE;

        // receive from rank 1 to rank n-1
        for (auto src = 1; src < MPI_SIZE; src++)
        {
            for (auto i = (SLICE_SIZE * src); (i < COLS) && (i < SLICE_SIZE * (src + 1)); i++)
            {
                auto temp = new MPI_Request();
                MPI_Irecv(current[i], ROWS, MPI_DOUBLE, src, 1, __WORLD, temp);
                requests->push_back(temp);
            }
        }
    }
    else // Workers send data to manager
    {
        // index 0 and COLS + 1 are ghost columns
        for (auto i = 1; i <= COLS; i++)
        {
            auto temp = new MPI_Request();
            MPI_Isend(current[i], ROWS, MPI_DOUBLE, 0, 1, __WORLD, temp);
            requests->push_back(temp);
        }
    }
    // wait for sync to finish
    waitAll(requests);

    requests->clear();
    delete requests;
    requests = nullptr;
}

// waits for all MPI requests and deletes the vector
void waitAll(std::vector<MPI_Request*>*& requests)
{
    for (auto& req : *requests)
    {
        MPI_Status stat;
        MPI_Wait(req, &stat);
        if (stat.MPI_ERROR != MPI_SUCCESS)
        {
            std::cerr << "MPI Request failed!\n\tCode: " << stat.MPI_ERROR
                      << "\n\tFrom: " << stat.MPI_SOURCE;
        }
        delete req;
    }
}


texts:
I have a Python script for doing "safe" file copying.

There are a couple of rules for this copy function:

Existing files should never be overwritten. So if I try to copy $file1 to $location, and there is already $file2 at $location, then $file2 will not be overwritten.
Exact filenames are not important. So if I try to copy a file to $location.txt, and because there’s already a different file there, it instead gets copied to $location-1.txt, that’s okay.
Copying should be idempotent. That is, if I try to copy a file to $location, and it's already there, nothing else happens. I'm not going to create more copies at $location-1, $location-2, $location-3, etc.

An example use case: I'm importing some camera photos into a folder, but some of the photos may be duplicates (and I don't want two copies) or have the same filename as another photo (and I want to keep both, but small changes to the name aren't important).

import filecmp
import os
import shutil

def increment_filename(filename, marker="-"):
    """Appends a counter to a filename, or increments an existing counter."""
    basename, fileext = os.path.splitext(filename)

    # If there isn't a counter already, then append one
    if marker not in basename:
        components = [basename, 1, fileext]

    # If it looks like there might be a counter, then try to coerce it to an
    # integer and increment it. If that fails, then just append a new counter.
    else:
        base, counter = basename.rsplit(marker, 1)
        try:
            new_counter = int(counter) + 1
            components = [base, new_counter, fileext]
        except ValueError:
            components = [base, 1, fileext]

    # Drop in the marker before the counter
    components.insert(1, marker)

    new_filename = "%s%s%d%s" % tuple(components)
    return new_filename

def copyfile(src, dst):
    """Copies a file from path src to path dst.

    If a file already exists at dst, it will not be overwritten, but:

     * If it is the same as the source file, do nothing
     * If it is different to the source file, pick a new name for the copy that
       is distinct and unused, then copy the file there.

    Returns the path to the copy.
    """
    if not os.path.exists(src):
        raise ValueError("Source file does not exist: {}".format(src))

    # Create a folder for dst if one does not already exist
    if not os.path.exists(os.path.dirname(dst)):
        os.makedirs(os.path.dirname(dst))

    # Keep trying to copy the file until it works
    while True:

        # If there is no file of the same name at the destination path, copy
        # to the destination
        if not os.path.exists(dst):
            shutil.copyfile(src, dst)
            return dst

        # If the namesake is the same as the source file, then we don't need to
        # do anything else
        if filecmp.cmp(src, dst):
            return dst

        # There is a namesake which is different to the source file, so pick a
        # new destination path
        dst = increment_filename(dst)

    return dst

Particular areas I’m unsure about:

Does it make sense? Is it clear what the code is doing?
Can I replace any of this with standard library functions?
I wrote it in Python 2, but will run it in 2 and 3. Brief testing suggests that it runs fine in Python 3, but pointers to anything I've missed would be helpful.
Is this good Python?


texts: Algorithm for two languages that merges and sorts two arrays without mutating one

texts:
This algorithm, which I have included its flowchart as well, takes an array of A[n], which is unsorted and unmutatable and an array of B[k], which is sorted and includes n zeroes and then merges, and sorts them together. The entire code in Python and C# can be found here and on this very post.

In C#:

class Program
{
    static void Main(string[] args)
    {
        var inputA = Console.ReadLine();
        var inputB = Console.ReadLine();

        char[] delimiter = { ' ', ',', '-' };
        string[] inputASplit = inputA.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
        string[] inputBSplit = inputB.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);

        int[] listA = new int[inputASplit.Length];
        int[] listB = new int[inputBSplit.Length];

        for (int i = 0; i < inputASplit.Length; i++)
        {
            listA[i] = int.Parse(inputASplit[i]);
        }

        for (int i = 0; i < inputBSplit.Length; i++)
        {
            listB[i] = int.Parse(inputBSplit[i]);
        }

        int[] concatinatedList = MergeSort(listA, listB);

        foreach (var number in concatinatedList)
        {
            Console.WriteLine(number);
        }

        Console.ReadKey();
    }

    static int[] ParseListA(int[] ListA)
    {
        List<int> newListA = ListA.ToList();
        newListA.Sort();

        return newListA.ToArray();

    }

    static int CountZeros(int[] ListB)
    {
        int zeroCount = 0;

        for (int i = 0; i < ListB.Length; i++)
        {
            if (ListB[i] == 0)
            {
                zeroCount += 1;
            }
        }

        if (zeroCount == 0)
        {
            throw new Exception("List B doesn't contain any Zeroes.");
        }

        return zeroCount;
    }

    static int[] MergeSort(int[] listA, int[] listB)
    {
        int[] newListA = ParseListA(listA);
        int zeroCount = CountZeros(listB);
        int[] newListB = new int[listB.Length - zeroCount];

        if (newListA.Length != zeroCount)
        {
            throw new Exception("There weren't enough buffers!");
        }

        for (int i = 0; i < listB.Length; i++)
        {
            if (listB[i] != 0)
            {
                for (int j = 0; j < newListB.Length; j++)
                {
                    newListB[j] = listB[i];
                }
            }
        }

        int[] concatenatedList = newListA.Concat(newListB).ToArray();
        Array.Sort(concatenatedList);

        return concatenatedList;
    }

In Python:

def ParseListA(listA):
    newListA = sorted(listA);

    return newListA;

def MergeSort(listA, listB):
    newListA = ParseListA(listA);
    zeroCount = 0;

    for number in listB:
        if number == 0:
            zeroCount += 1;

    if zeroCount == 0:
        raise ValueError("Needs zeros!");
        return;

    newlistB = [i for i in listB if i != 0];

    return sorted(newListA+newlistB);

def Main():
    listAInput = input("Enter List A: ").split(' ');
    listBInput = input("Enter List B: ").split(' ');

    listA = [int(i) for i in listAInput];
    listB = [int(i) for i in listBInput];

    print(MergeSort(listA, listB));

Main()


texts: Compiling all Exception messages into a string

texts:
Below is a recursive function I've written that's responsible for compiling a string consisting of a Exception's message, and also each of that Exception's InnerException messages.

I've tried to condense everything to one line, but am unsure if this is the most efficient way of approaching this problem.

public static string GetExceptionMessages(Exception exception, int msgCount = 1)
{
    return exception != null ? string.Format("{0}: {1}\n{2}", msgCount, exception.Message, GetExceptionMessages(exception.InnerException, ++msgCount)) : string.Empty;
}

And here is code showing the above method in action:

public static void Main(string[] args)
{
    try
    {
        Throw1();
    }
    catch (Exception e)
    {
        string messages = GetExceptionMessages(e);
        Console.WriteLine(messages);
    }
    Console.ReadLine();
}
public static void Throw1()
{
    try
    {
        Throw2();
    }
    catch (Exception e)
    {
        throw new Exception("Throw1", e);
    }
}
public static void Throw2()
{
    throw new Exception("Throw2");
}
public static string GetExceptionMessages(Exception exception, int msgCount = 1)
{
    return exception != null ? string.Format("{0}: {1}\n{2}", msgCount, exception.Message, GetExceptionMessages(exception.InnerException, ++msgCount)) : string.Empty;
}


texts:
I would like to know how I can improve this CakePHP 3.0 Component (inside folder controller)

1st: to use external libs (stored on vendor folder) I'm using the require keyword and include the class using use keyword, like this:

require_once(ROOT . DS . 'vendor' . DS . 'CakePHP-ImageTool-Component' . DS . 'ImageTool.php');

and

use ImageTool;

2nd: in method saveFileLFS I'm using true or false to flag OK.

<?php
namespace App\Controller\Component;

require_once(ROOT . DS . 'vendor' . DS . 'CakePHP-ImageTool-Component' . DS . 'ImageTool.php');

use Burzum\FileStorage\Lib\StorageManager;
use Cake\Controller\Component;
use ImageTool;

class UploadFileComponent extends Component
{
    function resizeImage($settings)
    {
        $status = ImageTool::resize([
            'input' => $settings['input'],
            'output' => $settings['output'],
            'width' => $settings['width'],
            'height' => $settings['height'],
            'mode' => $settings['mode']
        ]);
        return $status;
    }

    public function saveFileLFS($stringSeparator, $storeName, $productName)
    {
        $key = $storeName . $stringSeparator . $productName . $stringSeparator .
            $this->request->data['Media']['file']['name'];
        if(StorageManager::adapter('Local')->write($key,
            file_get_contents($this->request->data['Media']['file']['tmp_name']))){
            return true;
        }else
       {
            return false;
        }
    }
}


texts:
Q: I have a Bank class containing multiple loan accounts (LoanAccount class). I've create a LoanAccountService that have the CRUD functionalities. My concerns are about how I implemented the update functionality.

Bank

public class Bank {
    private List<LoanAccount> loanAccounts;
}

Loan account

public class LoanAccount {
    private String id;
    private Integer numberOfInstallments;
    private LoanAccountType type;
    private Date creationDate;
    private BigDecimal loanAmount;
}

Service

public class LoanAccountService{

    private Bank bank;

    public LoanAccountService(Bank bank) {
        this.bank = bank;
    }

    public LoanAccount update(LoanAccount loanAccount) {
        Optional<LoanAccount> account = bank.getLoanAccounts()
                .stream()
                .filter(la -> la.getId().equals(loanAccount.getId()))
                .findAny();
        if (account.isPresent()) {
            account.get().setCreationDate(loanAccount.getCreationDate());
            account.get().setLoanAmount(loanAccount.getLoanAmount());

        account.get().setNumberOfInstallments(loanAccount.getNumberOfInstallments());
            account.get().setType(loanAccount.getType());
        } else {
            throw new IllegalArgumentException("The object does not exist.");
        }
        return loanAccount;
    }
}

When the method update is called with a LoanAccount containing an id that already exists in loanAccounts list, I want to update the existing object with the object loanAccount given as parameter.

Above is my implementation, but I feel like there should be better ways to do it.


texts:
This question specifically relates to the use of the class constants ABOVE and BELOW in the sample code below.

I have a few different classes that look like this:

class MyClass(object):
    ABOVE = 1
    BELOW = 0

    def __init__(self):
        self.my_numbers = [1,2,3,4,5]

    def find_thing_in_direction(self, direction, cutoff):
        if direction == self.ABOVE:
            return [n for n in self.my_numbers if n > cutoff]
        else:
            return [n for n in self.my_numbers if n < cutoff]

my_class = MyClass()
my_var = my_class.find_thing_in_direction(MyClass.ABOVE, 3)

If I have a handful of classes scattered across different .py files that each have their own ABOVE and BELOW, should I extract these constants to somewhere, or is it better to keep the constants within their own classes?

Is there a more Pythonic way to do this instead of using these class constants?


texts:
This is my solution to the FROGV problem on Codechef:

N,K,P = map(int,raw_input().split(' ')) # N: No of Inputs, K: highest possible jump, P: no of test cases
L = map(int,raw_input().split(' ')) # Takes in the N space separated inputs
Li = sorted(L)
Breaks = [] #Records the starting point a of pair a,b such that the jump from a to b is larger than k
for i in xrange(0,N-1):
    if Li[i+1]-Li[i] > K: # The difference basically gives the jump size
        Breaks.append(Li[i])
for i in xrange(0,P): # Checking over each pair
    a,b = map(int,raw_input().split(' '))
    a,b = a-1,b-1 # The pairs use numbering from 1 to n while python numbering is from 0 to n-1
    for Break_Pt in Breaks:
        if (abs(L[a]-L[b])>K) and (((L[a]<=Break_Pt and Break_Pt<L[b]) or (L[b]<=Break_Pt and Break_Pt<L[a]))): # If the jump from a to be is greater than K then it checks whether there is a break pt in between a and b.
            print 'No'
            break
    else:
        print 'Yes'

Codechef tells me that this code exceeds the time limit, but I couldn't find any way to improve the speed.


texts:
I was thinking about how to handle AJAX requests in a MVC environment in PHP in a easy way.

What I've come up is (without showing you the backend code):

$.ajax({
    // url is empty so the request goes to the current route and controller
    // each controller (extended from base controller) checks every request to
    // see if it's an AJAX one. If it is it calls the Model/method specified bellow
    url:'',
    method:'POST',
    data: {
        toCall: 'User@create', // Calls model "User" with method "create"
        args: userData // arguments for method "create"
    },
    success: function(r) {
        // return JSON or true/false
    }
});

So basically the key is this "toCall: 'User@create'" line. which calls models directly. Should that be avoided because of security? Is it possible for a user to somehow change this "User@create" to access other models and methods?

Is my question clear?


texts: Acquiring an increasing sequence of numbers

texts:
I'm trying to solve this question:

  Given a positive integral number n, return a strictly increasing
  sequence (list/array/string depending on the language) of numbers, so
  that the sum of the squares is equal to n².

  If there are multiple solutions (and there will be), return the result
  with the largest possible values:

Basically, a squared number deconstructed into smaller squares. However, my code only works for smalls numbers efficiently (20 being roughly the max) and is exponentially slower onwards. How can I develop this code?

I tried optimising it by reducing the memory usage by setting comb to take out any bits of irrelevant data.

import itertools as it
from math import sqrt

def decompose(n):
    squares = [i ** 2 for i in range(1, n) if (i ** 2)/2 < n ** 2]
    comb = [list(i) for i in (reduce(lambda acc, x: acc + list(it.combinations(squares, x)),
                                     range(1, len(squares) + 1), [])) if sum(i) == n ** 2]
    print [int(sqrt(i)) for i in max(comb)]

decompose(20)

I am a beginner with Python so any optimisation tips will be greatly appreciated.


texts:
I am writing this small tester program to be used as part of a larger project, and I am quite unsure about the strtok function, which I (think) I need to use to split some character arrays up on a certain character (in my case this is a colon). For each character array (which is passed in as an argument), it should split the array into two. Apologies if it's hard to follow, I'm bad at explaining things.

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

int main(int argc, char **argv)
{
    char *pt;

    for (int i = 1; i < argc; i++)
    {
        pt = strtok(argv[i], ":");

        int j = 0;

        while (pt != NULL || j < 2)
        {
            j++;

            if (j == 1)
            {
                printf("item: ");
            } else if (j == 2)
            {
                printf("quantity: ");
            }

            printf("%s\n", pt);
            pt = strtok(NULL, ":");
        }

        j = 0;
    }

    return 0;
}

Yes, I know the program will crash if not enough arguments are supplied, but I just quickly threw this together to try and learn more about strtok. Now although this code works, I feel it is not the most efficient. I have not been programming C for very long, so any help for how I could improve this loop would be greatly appreciated.


texts: Generating a performance report for clans in Clash Royale

texts:
The following code generates a report showing performance of clan members in a game called Clash Royale.
Everything is pretty self-explanatory, we are working with a lot of https requests, arrays and sorting.
const https = require("https");
const clanTag = "L2P8GRJR";
const token = "TOKEN_HERE"

let rawData = '';
let topDonators = [];
let worstDonators = [];
let bestPlayers = [];
let counter = 0;
const mergeByProperty = (target, source, prop) => {
    source.forEach(sourceElement => {
        let targetElement = target.find(targetElement => {
            return sourceElement[prop] === targetElement[prop];
        })
        targetElement ? Object.assign(targetElement, sourceElement) : null;
    })
}

const finalise = () => {
    if (counter !== 2) return;

    let result = `CR Clan Youtube Weekly Report
°•°•°•°•°•°•°•°•°•°•°•°•

— Top Donators ——
~~~~~~~~~~~~~~~~~~
${topDonators.map((x, i) => `${i + 1}. ${x.name} - ${x.donations}`).join('\n')}
--------------------

— Back Donators ( < 100 ) ——
~~~~~~~~~~~~~~~~~~~
${worstDonators.map((x, i) => `${50 - i}. ${x.name} - ${x.donations}`).join('\n')}
--------------------

— Net Best Players ——
(Donations × Fame earned ÷ (100 × 1000))
===================
${bestPlayers.map((x, i) => `${i + 1}. ${x.name} - ${x.netScore}`).join('\n')}
===================

{ ${bestPlayers[0].name} } is the player of the week, congrats!

Data automatically fetched and compiled at ${new Date().toUTCString()}.

Earn fame in river race and donate cards to improve your net score which will be published on Sunday. Player of The Week will be chosen based on net score. Better net score may also result in promotion.

CR may not show full report to some players, hence this report is also published to the Discord server (link in the description).`
    console.log(result)
}

https.get(`https://proxy.royaleapi.dev/v1/clans/%23${clanTag}/members`, {
    headers: {
        authorization: token
    }
}, (res) => {
    res.on("data", (data) => {
        rawData += data
    })
    res.on("end", () => {
        rawData = JSON.parse(rawData).items

        topDonators = [...rawData].sort((a, b) => b.donations - a.donations).slice(0, 10)

        rawData.forEach(elm => {
            if (elm.donations < 100) worstDonators.push(elm)
        })
        worstDonators.sort((a, b) => a.donations - b.donations)
        counter++;
        finalise()
    })
})

https.get(`https://proxy.royaleapi.dev/v1/clans/%23${clanTag}/currentriverrace`, {
    headers: {
        authorization: token
    }
}, res => {
    let warData = [];
    res.on("data", data => {
        warData += data
    })

    res.on("end", () => {
        warData = JSON.parse(warData).clan.participants;
        mergeByProperty(rawData, warData, "tag")

        bestPlayers = [...rawData].map(elm => {elm.netScore = elm.fame * elm.donations / 100000; return elm;}).sort((a,b) => b.netScore - a.netScore).slice(0, 10)
        counter++;
        finalise()
    })
})

A proxy is being used but just know that that's a necessity.
Performance is the main point here but I would love review on any and every point.


texts: Resetable async Observable subscription that won't naturally dispose itself

texts:
I wanted to have a code review on the following Observable implementation, because there are many opinions and this one might not be the most efficient one. I would like to hear yours thoughts.
What I know

I know it's better to use .Select or .SelectMany instead of .Do, because Do doesn't support asynchronous delegates, since the lambda passed is async void. In addition, Select and SelectMany are handling the exceptions, which Do doesn't.

I know that Observable.Timer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1)) can be written as Observable.Interval. That's not the case here, it's just an example of something that won't naturally be disposed by itself and has to be handled manually.

I'm using a Subject<T> instead of IDisposable because I want to be able to reset the subscription at some point, just like here (@Enigmativity's post).

Snippet
public class TestClass2 : IDisposable
{
    private readonly Subject<IObservable<Unit>> _subject = new Subject<IObservable<Unit>>();

    public void Test()
    {
        _subject.Switch().Subscribe();

        var sub = Observable.Timer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1))
            .SelectMany(_ => Observable.FromAsync(async () =>
            {
                Console.WriteLine("Test");

                await Task.Delay(100);
            }));

        _subject.OnNext(sub);
    }

    public void Dispose()
    {
        _subject.OnNext(Observable.Never<Unit>());

        Console.WriteLine("Disposed");
    }
}


texts: Simple random number guessing game with various difficulties

texts:
I have been studying C#, and I am trying to model the Random number guessing game.

1 User inputs the number of try.
2 Computer generates random number.
3 If numbers doesn't match user lose one try
and if they match user gets two bonus try.

Is my program reasonable or is there anything I need to improve?

As player goes to next round, I also want
to increase random number range by 100 to increase
difficulty.For example, first round 1-100
next round 1-200 and so on.
How can I do that? Any help would be appreciated.

 public class GuessGame
 {

    public class Game
    {
        public int attemp { set; get; } = 0;
        public override string ToString()
        {
           return $"The player's attemp <{attemp}>";
        }
    }
    public static void Test()
    {
        Console.WriteLine("Lets play the Low or High Game");
        var game = new Game();

        game.attemp = InputAttempt();
        PlayGame(game);
    }
    public static void PlayGame(Game game)
    {
        Console.WriteLine(game);
        var comNum = GenerateComNum();
            Console.WriteLine($"This is for test: ComNum is {comNum}");
            do
            {
                var userNum = GenerateUserNum();
                CompareNum(userNum, comNum, game);
                Console.WriteLine(game);

            } while (game.attemp >0 );
     }

    static void CompareNum(int userNum, int comNum,Game game)
    {

        if (userNum < comNum)
        {
            Console.WriteLine("User num is too Low try again");
            Console.WriteLine();
            game.attemp--;
        }
        else if(userNum > comNum)
        {
            Console.WriteLine("User num is too High try again");
            Console.WriteLine();
            game.attemp--;
        }
        else if(userNum == comNum)
        {
            Console.WriteLine("You got the answer!!");
            Console.WriteLine();
            game.attemp += 2;
            PlayGame(game);
        }

    }
    static int GenerateUserNum()
    {
        int userNum;
        Console.Write("Please enter the num btw 1-100\t\t");
        while (!Int32.TryParse(Console.ReadLine(), out userNum))
        {
            Console.WriteLine("Invalid num please input whole num");
        }
        return userNum;
    }
    static int GenerateComNum()
    {
        Random rnd = new Random();
        var comNum = rnd.Next(1,101);
        return comNum;
    }
    static int InputAttempt()
    {
        var attempt = 0;
        Console.Write("How many Attemps would you like?\t");

        while (!Int32.TryParse(Console.ReadLine(), out attempt))
            {
                Console.WriteLine("Invalid num please input whole num");
            }
        return attempt;
    }
}


texts: Constructing objects for external libraries using a model in Laravel

texts:
I want to know if it's more appropriate to use a separate class (such as a factory?) to construct an object. While the code works, I am concerned about bloating of the model and the tight coupling.

To construct the said object I need:

environment variables like api tokens
some of the user's attributes from the model
classes from the library

Here's the relevant snippet within my user model that creates an AdWordsSession object for use in the third-party library:

class User extends Authenticatable {
...
   public function adWordsSession($customer_id = null){
        if(!$this->google_auth_token) {
            return null;
        }

        if( $this->adWordsSesssion &&
            (
                (isset($customer_id) && $this->adWordsSesssion->getClientCustomerId() == $customer_id) ||
                (!isset($customer_id) && $this->adWordsSesssion->getClientCustomerId() == $this->adwords_customer_id)
            )
        ){
            return $this->adWordsSesssion;
        }

        $oAuth2Credential = (new OAuth2TokenBuilder)
            ->withClientId(env('ADWORDS_CLIENT_ID'))
            ->withClientSecret(env('ADWORDS_CLIENT_SECRET'))
            ->withRefreshToken($this->google_auth_token)
            ->build();

        $session = (new AdWordsSessionBuilder())
            ->withDeveloperToken(env('ADWORDS_DEVELOPER_TOKEN'))
            ->withUserAgent(env('ADWORDS_USER_AGENT'))
            ->withClientCustomerId($customer_id ?: $this->adwords_customer_id)
            ->withOAuth2Credential($oAuth2Credential)
            ->build();

        $this->adWordsSesssion = $session;

        return $session;
    }
...
}

I am also interested to know if it applies to the reverse, using a class returned from the library (web service) to construct a model object. Should this be a static method of the model or a separate factory class. Code follows:

class AdWordsCampaign {
    public static function fromAdWordsClass(Campaign $campaign, AdWordsCampaign $adWordsCampaign = null): AdWordsCampaign {

        $self = $adWordsCampaign;

        if(is_null($adWordsCampaign)) {
            $self = new self;
            $self->criterions = $self->defaultCriterions();
            $self->extensions = $self->defaultExtensions();
        }

        if($campaign->getId()) {
            $self->fieldsHelper()->id = $campaign->getId();
            $self->setPublished();
        }

        $self->fieldsHelper()->name = $campaign->getName();
        $self->fieldsHelper()->status = $campaign->getStatus();
        $self->fieldsHelper()->advertisingChannelType = $campaign->getAdvertisingChannelType();
        $self->fieldsHelper()->advertisingChannelSubType = $campaign->getAdvertisingChannelSubType();

        $self->fieldsHelper()->budget = arrayify_object(
            $campaign->getBudget() ?
                $campaign->getBudget() :
                CampaignFields::defaultBudget()
        );

        return $self;
    }
}


texts:
Write a program to create a complete binary tree, which includes an addItem method such that an individual element can be inserted into the tree to maintain the property that tree is complete.

I'm looking for code review, optimizations and best practices. This code is attributed to GeeksForGeeks.

I am also not sure how to unit test this code. More specifically, how to generate the input to equals function.  The tree I would compare would be using the same addItem method which is destroying the whole purpose of unit testing.

public class CreateCompleteBinaryTree<T> {

    private TreeNode<T> root;

    public CreateCompleteBinaryTree(List<T> items) {
        for (T item : items) {
            addItem(item);
        }
    }

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

        TreeNode(T item) {
            this.item = item;
        }
    }

    /**
     * Adds item, such the tree is a complete binary tree.
     *
     * @param item the item to be added.
     */
    public void addItem(T item) {

        System.out.println(item);

        if (root == null) {
            root = new TreeNode<T>(item);
            return;
        }

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

        while (!queue.isEmpty()) {
            final TreeNode<T> currNode = queue.poll();

            if (currNode.left == null) {
                currNode.left = new TreeNode<T>(item);
                return;
            }

            if (currNode.right == null) {
                currNode.right = new TreeNode<T>(item);
                return;
            }

            queue.add(currNode.left);
            queue.add(currNode.right);
        }
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((root == null) ? 0 : root.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        CreateCompleteBinaryTree other = (CreateCompleteBinaryTree) obj;
        return equal(root, other.root);
    }

    private static boolean equal(TreeNode node1, TreeNode node2) {

        if (node1 == null && node2 == null) return true;
        if (node1 == null || node2 == null) return false;
        if (node1.item != node2.item) {
            System.out.println("---: " + node1.item + " : " + node2.item);
            return false;
        }

        return equal(node1.left, node2.left) && equal(node1.right, node2.right);
    }
}


texts: Couting numbers greater than given - using binary search

texts:
It's my first exercise involving the well-known binary search. The problem goes as follows: we are given a sequence of n numbers and we have to answer to t questions, each of which is: “How many numbers in the specified sequence are greater than the i-th element of the sequence?” For example, we have n = 3 and t = 3. Our sequence is 2, 1, 3. And we have to count numbers greater than the first (1), second (2) and third element of our sequence (3). The correct output is “1 2 0”.  I've already written some code… but it works only in some cases.

    #include <iostream>
#include <algorithm>

using namespace std;

template<typename T> int binSearch(const T& x, const T* array, size_t size)
{

int l = 0, p = size - 1, s;

while (l <= p)
{

s = (l + p) / 2;

if (array[s] == x)
return s;

if (array[s] > x)
p = s - 1;

else
l = s + 1;
}

return -1;
}

int main(){

    int n, t;

    cin >> n >> t;

    int a[n];

    int a_sorted[n];

    int questions[t];

    for (int i=0; i<n; i++){ cin >> a[i]; a_sorted[i]=a[i]; };

    for (int i=0; i<t; i++) cin >> questions[i];

    sort (a_sorted, &a_sorted[n]);

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

        int index=binSearch(a[questions[i]-1], a_sorted, n);

        int count_=n-(index+1);

        cout << count_ << endl;

    }

    return 0;

}

If my question is difficult to understand, feel free to ask for additional information – it wasn't easy to ask too ;)


texts: How can I refactor for handling multiple proto generated service clients by eliminating double await and the DRY code?

texts:
I'm having doubts about which is the best strategy to manage the many service clients in this web app.
"Best" in terms of a good compromise between user's device RAM and Javascript execution speed (main thread ops).
This is what I'm doing right now, this is the main file:

main.ts:

import type { PlayerServiceClient } from './player.client';
import type { TeamServiceClient } from './team.client';
import type { RefereeServiceClient } from './referee.client';
import type { FriendServiceClient } from './friend.client';
import type { PrizeServiceClient } from './prize.client';
import type { WinnerServiceClient } from './winner.client';
import type { CalendarServiceClient } from './calendar.client';

let playerService: PlayerServiceClient;
export const player = async (): Promise<PlayerServiceClient> =>
    playerService ||
    ((playerService = new (await import('./player.client')).PlayerServiceClient()),
    playerService);

let teamService: TeamServiceClient;
export const getTeamService = (): TeamServiceClient =>
    teamService ||
    ((teamService = new (await import('./team.client')).TeamServiceClient()),
  teamService);

let refereeService: RefereeServiceClient;
export const getRefereeService = (): RefereeServiceClient =>
    refereeService ||
  ((refereeService = new (await import('./referee.client')).RefereeServiceClient()),
  refereeService);

let friendService: FriendServiceClient;
export const getFriendService = (): FriendServiceClient =>
    friendService ||
  ((friendService = new (await import('./friend.client')).FriendServiceClient()),
  friendService);

let prizeService: PrizeServiceClient;
export const getPrizeService = (): PrizeServiceClient =>
    prizeService ||
  ((prizeService = new (await import('./prize.client')).PrizeServiceClient()),
  prizeService);

let winnerService: WinnerServiceClient;
export const getWinnerService = (): WinnerServiceClient =>
    winnerService ||
  ((winnerService = new (await import('./winner.client')).WinnerServiceClient()),
  winnerService);

let calendarService: CalendarServiceClient;
export const getCalendarService = (): CalendarServiceClient =>
    calendarService ||
  ((calendarService = new (await import('./calendar.client')).CalendarServiceClient()),
  calendarService);

// and so on... a lot more...

As you can see there are many service clients.
I'm using this code because I thought it was better given my web app structure based on routes almost overlapping with client services:
I mean, if the player goes from /home to /players page I can use it like this:

components/players.svelte

import { getPlayerService } from "main";

const playerService = await getPlayerService();
const players = await playerService.queryPlayers();

In this way, if the PlayerService does not exist, it is imported at the moment and returned, otherwise it returns the one imported and instantiated before.
Since the user switches pages frequently this way I can avoid the sudden creation and destruction of those clients, right?
But in this way I am using global variables which I don't like to use and I'm using verbose, DRY and long code in each component.
Is there a way to use the below code in components instead?
import { playerService } from "main";

const players = await playerService.queryPlayers();

What do you suggest me to do?


texts:
I'm refactoring my scheduler and for one of its triggers I need an endless counter that would automatically restart. Since this is a simple and very common task I don't want to ever have to implement it again so I encapsulated it in such a way that it hopefully can be reused everywhere else.

The counter is represented by an enumerable interface with a couple or properties that provide information about the counter and methods allowing to interact with it.

public interface IInfiniteCounter : IEnumerable<(int Value, InfiniteCounterState State)>
{
    int Min { get; }

    int Max { get; }

    int Length { get; }

    int Current { get; }

    (int Value, InfiniteCounterState State) Next();

    void Reset();
}

It uses an enum to inform the caller about the type of the value. It returns First each time the counter restarted, Intermediate for values inbetween and Last for the last value.

public enum InfiniteCounterState
{
    First,
    Intermediate,
    Last,
}

I have one implementation of the interface. The InfiniteCounter that is a forward running counter:

public class InfiniteCounter : IInfiniteCounter
{
    private int _current;

    public InfiniteCounter(int min, int max)
    {
        Min = min;
        Max = max;
    }

    public InfiniteCounter(int max) : this(0, max) { }

    public int Min { get; }

    public int Max { get; }

    public int Length => Max - Min;

    public int Current => _current + Min;

    private bool IsLast => _current == Length;

    public (int Value, InfiniteCounterState State) Next()
    {
        if (IsLast)
        {
            Reset();
        }

        return
        (
            Current,
            _current++ == 0
                ? InfiniteCounterState.First
                : IsLast
                    ? InfiniteCounterState.Last
                    : InfiniteCounterState.Intermediate
        );
    }

    public void Reset()
    {
        _current = 0;
    }

    public IEnumerator<(int Value, InfiniteCounterState State)> GetEnumerator()
    {
        while (true)
        {
            yield return Next();
        }
    }

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

In order to have it running backwards I created two extensions. One that is an extension for the IInfiniteCounter

public static class InfiniteCounterExtensions
{
    public static IEnumerable<(int Value, InfiniteCounterState State)> Countdown(this IInfiniteCounter counter)
    {
        return counter.Select(x => (x.Value.Flip(counter.Min, counter.Max), x.State));
    }
}

and one that is flipping the value:

public static class IndexMath
{
    public static int Flip(this int value, int min, int max)
    {
        return (-(value - max + 1) % (max - min)) + min;
    }
}

Examples:

void Main()
{
    var take = 4;
    new InfiniteCounter(3).Take(take).Dump("0-2");
    new InfiniteCounter(3).Countdown().Take(take).Dump("2-0");
    new InfiniteCounter(2, 5).Take(take).Dump("2-4");
    new InfiniteCounter(2, 5).Countdown().Take(take).Dump("4-2");

    0.Flip(0, 3).Dump();
    1.Flip(0, 3).Dump();
}

What do you think about it? It should be convenient to use and every piece of it should be testable. (Argument checking will be added later)


texts: How can I optimize this database to array structure code?

texts:
I need to take data from a MySQL database and message it into a format expected by the front end of an application - I can not change the front end as other services provide it data in this same format.

The database is structured as follows:

id   type     value     label         optgroup
1    car      ix5       Ford Taurus   Ford
2    car      ix6       Ford Focus    Ford
3    car      ix9       Cobalt        Chevy
4    planet   ix8       Earth         Default

The output from this code must do the following: for types with optgroups, records must be categorized by optgroup; if there is only one optgroup, then it should be ignored. The real data has hundreds to thousands of rows per type. The finally array output from this data would be:

$data = [
    'car' => [
        'chevy' =>  [ 'ix9' => 'Cobalt' ],
        'ford'  =>  [ 'ix5' => 'Ford Taurus', 'ix6' => 'Ford Focus' ]
    ],
    'planet' => [ 'ix8' => 'earth' ]
];

The code I have doing this currently works, but is a bit slow, and I am looking for a possible improvement.  Here's the functioning code, where $STH->result() is the database result as an array of rows:

protected function _format($STH)
{
    $data = [];

    foreach ($STH->result() as $row)
    {
        if ( ! $row->optgroup)
            $data[ $row->type ][ $row->value ] = $row->label;
        else
            $data[ $row->type ][ $row->optgroup ][ $row->value ] = $row->label;
    }

    // selects with a single optgroup can have that optgroup removed
    foreach ($data as $menutype => $optorkey)
    {
        if (is_array($optorkey) && count($optorkey) == 1)
            $data[$menutype] = current($optorkey);
    }

    return $data;
}

EDIT

The original query generating the data is very simple, as follows:

SELECT type, value, label, optgroup FROM ####.options ORDER BY type, optgroup, label ASC

The data in this table is updated frequently by automated processes.


texts: Find the smallest divisible number for the given input 'n' such that number is evenly divisible by 1 to n

texts:
Given a number n, the task is to complete the function which returns an integer denoting the smallest number evenly divisible by each number from 1 to n.

I have solved it using the following function:

long long getSmallestDivNum(long long n)
{
   //number should be multiplier of n
    bool found = true;
    int i = 2;
    while(1)
    {
        long long r = n*i;
        found = true;
        for(int j=2;j<=n;j++)
        {
            if( r % j != 0)
            {
                found  = false;
            }
        }
        if(found != true)
        {
            i++;
        }
        else
        {
            return r;
        }
    }
}

But I am getting a time-limit-exceeded-error like this:

  Run Time Error Time Limit of 5 seconds exceeded.

When I execute the code in my local NetBeans, it works fine with a runtime of 62ms.


texts: Python script using distutils to copy files on a Mac

texts:
I have a Python script I have written to copy files to a mounted Windows SMB share on a Mac.

import os
import distutils.core
# Create a local site for the mount to reside
directory = "/Users/username/share"
if not os.path.exists(directory): os.makedirs(directory)
# Mount the Windows smb share
os.system("mount_smbfs //service.account:password@server.domain.com/share ~/share")
# set source and destination
fromDirectory1 = "/Volumes/Macintosh HD/folder1/folder2/folder3"
fromDirectory2 = "/Volumes/Macintosh HD/folder4/folder5/folder6"
fromDirectory3 = "/Volumes/Macintosh HD2/folder1/folder2"
fromDirectory4 = "/Volumes/Macintosh HD2/folder1/folder3/folder4"
toDirectory1 = "/Users/username/share/folder3"
toDirectory2 = "/Users/username/share/folder6"
toDirectory3 = "/Users/username/share/folder2"
toDirectory4 = "/Users/username/share/folder4"
#Do the copying
distutils.dir_util.copy_tree(fromDirectory1, toDirectory1)
distutils.dir_util.copy_tree(fromDirectory2, toDirectory2)
distutils.dir_util.copy_tree(fromDirectory3, toDirectory3)
distutils.dir_util.copy_tree(fromDirectory4, toDirectory4)
#Unmount the share
os.system("umount ~/share")

I understand the script is verbose but I wrote it this way to # out lines to problem solve. Can you suggest a cleaner way to write it?

Any insights gratefully received.

Version 2:

import os
import distutils.core

# Create a local site for the mount to reside
directory = "/Users/username/share"
if not os.path.exists(directory): os.makedirs(directory)

# Mount the Windows smb share
os.system("mount_smbfs //service.account:password@server.domain.com/share ~/share")

# set source and destination
copy_jobs = []
copy_jobs.append({"from": "/Volumes/Macintosh HD/folder1/folder2/folder3", "to": "/Users/username/share/folder3"})
copy_jobs.append({"from": "/Volumes/Macintosh HD/folder4/folder5/folder6", "to": "/Users/username/share/folder6"})
copy_jobs.append({"from": "/Volumes/Macintosh HD2/folder1/folder2", "to": "/Users/username/share/folder2"})
copy_jobs.append({"from": "/Volumes/Macintosh HD2/folder1/folder3/folder4", "to": "/Users/username/share/folder4"})

#Do the copying
for job in copy_jobs:
    distutils.dir_util.copy_tree(job["from"], job["to"])

# Unmount the Windows smb share
os.system("umount ~/share")


texts: Basic expressive Swift background thread execution

texts:
I created a basic background thread class in swift to replace the ugliness of:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
  // background thread code
  dispatch_async(dispatch_get_main_queue()) { () -> Void in
      // done, back to main thread
  }
}

with the expressiveness of:

Background { () -> () in
    // background code
  }.afterInterval(3) { () -> () in
    // main thread, run after interval IF not done
  }.completion { () -> () in
    // done, main thread
  }

afterInterval and completion are optional and interchangeable.

How reliable is this approach? Can we ever return from init(task) before completion is added, using the dot syntax? I have tested to my abilities and it seems rather bulletproof, but am wondering about the thoughts here.

class Background {

  private var done = false {
    didSet {
      if done {
        taskInterval = nil
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
          completion?()
        }
      }
    }
  }

  private var taskInterval: (() -> ())?
  private var completion: (() -> ())?

  init(task: () -> ()) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
      task()
      self.done = true
    }
  }

  func afterInterval(interval: NSTimeInterval, closure: () -> ()) -> Background {
    taskInterval = closure
    let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(interval * Double(NSEC_PER_SEC)))
    dispatch_after(delayTime, dispatch_get_main_queue()) { [weak self] in
      self?.taskInterval?()
    }
    return self
  }

  func completion(closure: () -> ()) -> Background {
    completion = closure
    return self
  }

}

"SwiftyThreads" on Github


texts: Optimal change with only with two euros coins and five and ten euros bills

texts:
We assume we have unlimited number of coins and bills. My code works fine but the method optimalChange() has a Cyclomatic Complexity of 8.

import java.util.*;
import java.math.*;

class Change {
   long coin2 = 0;
   long bill5 = 0;
   long bill10 = 0;
}

class Solution {

  static Change optimalChange(long s) {
    long change = s;
    Change c = new Change();
    if (change >=10) {
        if (change % 2 != 0 && change % 5 !=0) {
            return dealWithChangeLike31Euros(change);
        }
        else {
            c.bill10 = (long) change / 10;
            change = change % c.bill10;
        }
    }

    if (change <10 && change >=5) {
        if (change % 2 == 0) {
            c.bill5 = 0;
            c.coin2 = change/2;
        }
        else {
            change = change - 5;
            c.bill5 = 1;
        }
    }

    else if (change %2 ==0) {
        c.bill5 = 0;
        c.coin2 = change/2;
    } else {
        return null;
    }
    return c;
  }

  static Change dealWithChangeLike31Euros(long s) {
    Change c = new Change();
    c.bill10 = ((long) s / 10) - 1;
    long change = (long) s % (c.bill10 * 10);
    if (change > 5) {
        change = change - 5;
        c.bill5 = 1;
    }
    if (change % 2 == 0) {
        c.coin2 = change / 2;
    }
    else {
        return null;
    }
    return c;
  }
}

Can the implementation of the dealWithChangeLike31Euros() method be merged into the other method?


texts:
Since I've been working with C strings these days, I decided to make a string class from the ground-up just to see how it would go. I wrote all labels in Spanish (my mother language) just for the sake of it. If you have problems understanding it, I'll simply translate them into English

(DISCLOSURE: I'm not thinking about actually using this in production code. I was just trying something new. I think the native std::string class is much better for these things. But if you can tell me how this would perform in production code, it would be of great help!).

My main goal was to made a class that could be edited and used with legacy code that needs a const char* instead of std::string.

What do you think about it? I have some doubts about my implementation: for instance, I don't know if returning the buffer as const char* is safe, or if using static_cast is necessary.

Here is my header file (Cadena.h):

#pragma once
#include <iostream>

namespace David {

    class Cadena {
    private:
        char* bufer;
        size_t tamanio;

        size_t obtenerLongitud(const char* cadena) {
            size_t longitud = 0;
            for (longitud = 0; cadena[longitud] != '\0'; ++longitud);
            ++longitud;
            return longitud;
        }

        void borrarBufer() {
            delete[] bufer;
            bufer = nullptr;
        }

        void ajustar(size_t longitud) {
            char* cadenaTemporal = new char[longitud + 1];
            if (bufer != nullptr) {
                for (size_t i = 0; i < tamanio; ++i) {
                    cadenaTemporal[i] = bufer[i];
                }
            }
            borrarBufer();
            bufer = cadenaTemporal;
            cadenaTemporal = nullptr;
            tamanio = longitud + 1;
        }

    public:
        Cadena(const char* cadena) {
            tamanio = obtenerLongitud(cadena);
            bufer = new char[tamanio];
            for (size_t longitud = 0; cadena[longitud] != '\0'; ++longitud) {
                bufer[longitud] = cadena[longitud];
            }
            bufer[tamanio - 1] = '\0';
        }

        Cadena() {
            tamanio = 0;
            bufer = nullptr;
        }

        ~Cadena() {
            borrarBufer();
        }

        const char* formaConstante() const {
            return static_cast<const char*>(bufer);
        }

        const size_t len() const {
            return tamanio - 1;
        }

        char& operator [] (size_t indice) {
            if (indice < tamanio)
                return bufer[indice];
            return bufer[tamanio - 1];
        }

        void operator = (const char* cadena) {
            borrarBufer();
            tamanio = obtenerLongitud(cadena);
            bufer = new char[tamanio];
            for (size_t longitud = 0; cadena[longitud] != '\0'; ++longitud) {
                bufer[longitud] = cadena[longitud];
            }
            bufer[tamanio - 1] = '\0';
        }

        friend std::ostream& operator << (std::ostream& salida, const Cadena& cadena) {
            for (size_t longitud = 0; cadena.formaConstante()[longitud] != '\0'; ++longitud) {
                salida << cadena.formaConstante()[longitud];
            }
            return salida;
        }

        friend void operator >> (std::istream& entrada, Cadena& cadena) {
            if(cadena.bufer != nullptr) cadena.borrarBufer();
            char letra = ' ';
            size_t longitud = 0;
            while (letra != '\n') {
                entrada >> std::noskipws >> letra;
                cadena.ajustar(longitud);
                cadena.bufer[longitud] = letra;
                ++longitud;
            }
            cadena.bufer[longitud - 1] = '\0';
        }
    };

}


texts: LeetCode 1320: Minimum Distance to Type a Word Using Two Fingers II

texts:
I'm posting my Python code for LeetCode's 1320. If you have time and would like to review, please do so.
Problem

You have a keyboard layout as shown above in the XY plane, where each English uppercase letter is located at some coordinate, for
example, the letter \$A\$ is located at coordinate \$(0,0)\$, the letter
\$B\$ is located at coordinate \$(0,1)\$, the letter \$P\$ is located at
coordinate \$(2,3)\$ and the letter \$Z\$ is located at coordinate
\$(4,1)\$.

Given the string word, return the minimum total distance to type such string using only two fingers. The distance between coordinates
\$(x_1,y_1)\$ and \$(x_2,y_2)\$ is \$|x_1 - x_2| + |y_1 - y_2|\$.

Note that the initial positions of your two fingers are considered free so don't count towards your total distance, also your two fingers
do not have to start at the first letter or the first two letters.

Example 1:
Input: word = "CAKE" Output: 3
Explanation:
Using two fingers, one optimal way to type "CAKE" is:

Finger 1 on letter 'C' -> cost = 0
Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2
Finger 2 on letter 'K' -> cost = 0
Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1

Total distance = 3
Constraints:

\$2 \le \text{word.length} \le 300\$
Each word[i] is an English uppercase letter.

Accepted Python
import string
import functools

class Solution:
    def minimumDistance(self, word: str) -> int:
        WIDTH = 6
        A_DECIMAL = 65
        def get_coordinates(left: int, right: int) -> int:
            if not left or not right:
                return 0

            x_left, y_left = indices[left]
            x_right, y_right = indices[right]

            return abs(x_left - x_right) + abs(y_left - y_right)

        @functools.lru_cache(None)
        def get_dp(index, word_a: str = None, word_b: str = None) -> None:
            if index == len(chars):
                return 0

            dist_a = get_coordinates(word_a, chars[index]) + get_dp(index + 1, chars[index], word_b)
            dist_b = get_coordinates(word_b, chars[index]) + get_dp(index + 1, word_a, chars[index])

            return min(dist_a, dist_b)

        chars = ''.join(a for a, b in zip(word, word[1:] + ' ') if a != b)
        indices = {char: divmod((ord(char) - A_DECIMAL), WIDTH) for char in string.ascii_uppercase}
        return get_dp(0)

Reference
On LeetCode, there is a class usually named Solution with one or more public functions which we are not allowed to rename.

Problem

Discuss


texts:
I tried this problem and I saw that my solutions was way too slow compared to others. I want to know how I can improve time complexity.

  A job has been assigned to Jar Jar Binks, it goes as follows: There
  are N spaceships parts, each with a weight of Wi kg. Given a weight W,
  he has to show how many parts can be used in order to make a ship with
  a weight of exactly W kg. He has to show all possible solutions, of
  course if possible. Everybody knows Jar Jar Binks particularly because
  of his clumsiness, so you have to help him. Write a program that
  solves his problem!

  Input

  There will be several cases, each beginning with two integers N, Q
  (1<=N<=60, 0<=Q<=10000). Next there will be N positive integers
  representing the weights of the N spaceship parts (1<=Wi<=1000). Q
  lines will follow, each one with only one integer W, the total weight
  of the spaceship. End of input will be denoted with N = 0 and Q = 0.
  This case should not be processed

  Output

  Print a line with K integers per query in ascending order. They must
  represent the amount of pieces that can be used to make a spaceship
  with weight W. If there is no way to make a spaceship with weight W,
  output a line with the string “That's impossible!” (quotes to clarify)

#include <bits/stdc++.h> // I don't think this would have any impact on run-time , right?

using namespace std;

#define pb push_back

#define FOR(i,a,b) for(int i=a;i<=b;++i)

int a[60];
int dp[61][61][60001]; // dp[number of weights considered][no. of weights selected from earlier][if this sum is possible]
int main()
{
    ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); // for speed improvement

    int n,q;

    while(1)
    {
        cin>>n>>q;

        if(n==0&&q==0)break;

        int sum=0;
        FOR(i,1,n){cin>>a[i];sum+=a[i];}

        memset(dp,0,sizeof(dp));

        dp[0][0][0]=1;
        // I know that a 3d array is not needed but this would affect only memory, right?
        FOR(i,1,n)
        {
            dp[i][0][0]=1;
            FOR(j,1,i)
            {
                FOR(k,0,sum)
                {
                    if(k>=a[i])
                    dp[i][j][k]=dp[i-1][j-1][k-a[i]]; // typical dp. either a[i] is taken into account

                    dp[i][j][k]|=dp[i-1][j][k];       // or it is not
                }
            }
        }

        while(q--)    // handling queries
        {
            int x;
            cin>>x;
            vector<int> v;   // we will store answers here

            if(x>=1&&x<=sum)
            {
                FOR(j,1,n)
                if(dp[n][j][x])v.pb(j);

                if(v.empty())cout<<"That's impossible!";

                else for(auto it :v)cout<<it<<" ";

                cout<<"\n";
            }

            else cout<<"That's impossible!\n";
        }
    }
    return 0;
}