texts: My code changes a single RGB value by a set amount, then does the same changes over the other channels

texts:
So I have the following code, that takes an image and modifies the RGB channels one at a time. It then creates a list of 9 images with the various modified channels.
The Red channel is modified by 0.1, then by 0.5, then by 0.9. This is then applied to the Green channel then the Blue Channel.
Resulting in a list of 9 images with the same modifications, but to different channels. The code works, but I just feel like there is a lot of repetition, and this really bugs me.
#%%

from PIL import Image

# Set the file and open it
file = "Final/charlie.png"

#Create an empty list to append the images to
images = []

#Image processing function, depending on the counter
def image_processing0(a):
    if count == 0 or count == 3 or count == 6:
        c = int(a * 0.1)
        return c
    elif count == 1 or count == 4 or count == 7:
        c = int(a * 0.5)
        return c
    elif count == 2 or count == 5 or count == 8:
        c = int(a * 0.9)
        return c

#Set the count to 0
count = 0

#Create PixelMap
while count <9:
#Creat Pic at the start of each loop
    pic = Image.open(file)
#Convert the image to RGB, so we dont have to deal with the alpha channel
    pic = pic.convert('RGB')

#Get the RGB value for every pixel
    for x in range(pic.size[0]):
            for y in range(pic.size[1]):

                #Split the RGB value into variables r, g and b
                r,g,b = pic.getpixel((x,y))

#Check the count, use logic to appy the processing to the correct channel
                if count <3:
                    r = image_processing0(r)
                    pic.putpixel((x,y),(r,g,b))
                elif count < 6:
                    g = image_processing0(g)
                    pic.putpixel((x,y),(r,g,b))
                elif count < 9:
                    b = image_processing0(b)
                    pic.putpixel((x,y),(r,g,b))

#Add the images to the list
    images.append(pic)
#Increment the counter
    count+=1

Both my logic statement, and my function seem a bit repetitive:
 #---------------------------------------------------
    #Image processing function, depending on the counter
    def image_processing0(a):
        if count == 0 or count == 3 or count == 6:
            c = int(a * 0.1)
            return c

        elif count == 1 or count == 4 or count == 7:
            c = int(a * 0.5)
            return c

        elif count == 2 or count == 5 or count == 8:
            c = int(a * 0.9)
            return c
#---------------------------------------------------

#Check the count, use logic to apply the processing to the correct channel
if count <3:
    r = image_processing0(r)
    pic.putpixel((x,y),(r,g,b))

elif count < 6:
    g = image_processing0(g)
    pic.putpixel((x,y),(r,g,b))

elif count < 9:
    b = image_processing0(b)
    pic.putpixel((x,y),(r,g,b))
#---------------------------------------------------

I tried to change my logic to the following, but soon realized that when I put the pixel back, i had no way to specify exactly what channel I was placing back in the  pic.putpixel((x,y),(r,g,b)) statement.
if count <3:
    channel = r
elif count < 6:
    channel = g
elif count < 9:
    channel = b

channel = image_processing0(channel)
pic.putpixel((x,y),(r,g,b))    #No way to define which channel is being changed


texts:
I've developed a script to set up an encrypted tunnel between two Linux hosts, using iproute2, ssh and setkey.
The goal is to allow setting up ad-hoc secure tunnels with minimum of setup and dependencies.

Mirrored here:

#!/bin/bash

# Setup encrypted IPv4 tunnel over IPv4 or IPv6 on two Linux nodes using SSH for tunnel setup.
# Requires only ipsec-tools, iproute2, ssh and necessry kernel modules locally and remotely.

# Warning: it flushes IPsec settings both locally and remotely.
# Don't use with other IPsec tunnnels.

# Sample usage:
# simplevpn -6 fc::1 fc::2    ssh -T root@fc::2
#    fc::1 is your IPv6 address
#    fc::2 is other peer's IPv6 address
# after successful run it should create tunnel named "simplevpn" locally and remotely
# and set up addresses 192.168.77.1 and 192.168.77.2 locally and remotely respectively

# Note: tested only once in my configuration. This is not a serious production-ready VPN solution.

# Implemented by Vitaly "_Vi" Shukela in 2013, License=MIT

MODE="ipip"
PROT="-4"

if [ "$1" == "-6" ]; then
    shift;
    MODE=ipip6
    PROT="-6"
fi

SRC="$1"; shift
DST="$1"; shift

if [ -z "$1" ]; then
    echo Usage: simplevpn [-6] source_ip destination_ip ssh_command_line
    exit 1;
fi
set -e

KEY1=0x`dd if=/dev/urandom count=32 bs=1 2> /dev/null| xxd -p -c 64`
KEY2=0x`dd if=/dev/urandom count=32 bs=1 2> /dev/null| xxd -p -c 64`

true ${LOCALIP:="192.168.77.1"}
true ${REMOTEIP:="192.168.77.2"}
true ${DEVNAME:="simplevpn"}

# 4 is encapsulated IPv4 both in IPv4 an IPv6
setkey -c << EOF
    flush;
    spdflush;
    spdadd $SRC $DST   4 -P out ipsec esp/transport//require  ah/transport//require;
    spdadd $DST $SRC   4 -P in ipsec esp/transport//require  ah/transport//require;
    add $SRC $DST esp 0x4444 -E rijndael-cbc $KEY1 ;
    add $DST $SRC esp 0x4444 -E rijndael-cbc $KEY1 ;
    add $SRC $DST ah 0x4445 -A hmac-sha256 $KEY2 ;
    add $DST $SRC ah 0x4445 -A  hmac-sha256 $KEY2 ;
EOF

modprobe ip6_tunnel
ip $PROT tunnel del $DEVNAME || true

ip $PROT tunnel add  $DEVNAME mode $MODE local $SRC remote $DST
ip link set $DEVNAME up
ip -4 addr add $LOCALIP/32 dev $DEVNAME
ip -4 route add $REMOTEIP/32 dev $DEVNAME

"$@" << EOF
    set -e
    # the same as above, but "in" and "out" swapped
    setkey -c << EOF2
        flush;
        spdflush;
        spdadd $SRC $DST   4 -P in ipsec esp/transport//require  ah/transport//require;
        spdadd $DST $SRC   4 -P out ipsec esp/transport//require  ah/transport//require;
        add $SRC $DST esp 0x4444 -E rijndael-cbc $KEY1 ;
        add $DST $SRC esp 0x4444 -E rijndael-cbc $KEY1 ;
        add $SRC $DST ah 0x4445 -A hmac-sha256 $KEY2 ;
        add $DST $SRC ah 0x4445 -A  hmac-sha256 $KEY2 ;
EOF2

    modprobe ip6_tunnel
    ip $PROT tunnel del $DEVNAME || true

    ip $PROT tunnel add  $DEVNAME mode $MODE remote $SRC local $DST
    ip link set $DEVNAME up
    ip -4 addr add $REMOTEIP/32 dev $DEVNAME
    ip -4 route add $LOCALIP/32 dev $DEVNAME
EOF

Are there any glaring errors? Do you have any suggestions (apart from not flushing entire security tables)? I'm primarily interested in security issues.


texts: Greedy solution to minimize the max-min spread

texts:
I wrote this solution to contest challenge and I am new to D and was hoping for some tips to make it faster or more Dish.  The challenge is to select K integers from a list of N integers (2 ≤ N ≤ 105, each 0 ≤ xi ≤ 109) such that the max(xi) – min(xi) is minimized.  The first line of input contains N, the second line contains K, and subsequent lines contain the xi.

import std.stdio;
import std.array;
import std.range;
import std.conv;
import std.algorithm;

void main(){
    auto input = stdin.byLine().map!( a => to!int(a.idup) ).array;
    auto n = input[0];
    auto k = input[1];

    input = input[2..$].sort;

    uint i = -1;
    auto unfairness = uint.max;
    while(++i + k <= n){
        auto localUnfairness = input[i+k-1] - input[i];
        if(unfairness > localUnfairness) unfairness = localUnfairness;
    }

    writeln(unfairness);
}

// greybeard is a fugging tool


texts:
We've had a situation whereby we have to cater for certain exceptions and retry a particular method whenever these exceptions occur. This is required in various parts of the system. In addition, we (might) want to invoke a 'callback' upon the need to retry.

I'll show you the code, then give you an example of useage:

    public static void InvokeActionWithRetry(Action action, int retryAttempts, Action retryCallback = null, params Type[] exceptionTypes)
    {
        do
        {
            try {
                action();
                break;
            }
            catch (Exception ex)
            {
                   if ((exceptionTypes?.Length > 0 && exceptionTypes.Contains(ex.GetType()))
                        || retryAttempts == 0)
                    throw;

                if (retryCallback != null)
                    retryCallback();
            }

            retryAttempts--;
        }
        while (retryAttempts >= 0);
    }

So, an example (although not a real-world one), may be:

ActionHelper.InvokeActionWithRetry(() => {
    Print(document);
},
5,
() => {
    RebootPrinter();
},
typeof(PrinterNeedsRestartException));

Is there anything that can be improved with the static method I've written?

I'm pretty new to using actions/funcs so I'm open to suggestions about how I can refactor this.

I also feel the type evaluation is a little 'hacky'.

EDIT:

I just noticed I'm not checking the types collection passed in prior to calling Contains on it. Naughty. I'll rework that bit and update the question.


texts: Select multiple count queries in single query

texts:
I currently have 6 very similar queries that I'm trying to increase performance on by making them all subqueries in 1 query. I'm not sure what is better performance wise, keeping them 6 separate queries, 1 query with 6 subqueries (as shown below), or some other method that I'm unfamiliar with.

SELECT
  (SELECT COUNT(*) FROM table_one WHERE date=myDate AND name=myName) AS total,
  (SELECT COUNT(*) FROM table_one WHERE date=myDate AND name=myName AND CODE_A BETWEEN 100 AND 199) AS code_a_low_count,
  (SELECT COUNT(*) FROM table_one WHERE date=myDate AND name=myName AND CODE_A BETWEEN 200 AND 299) AS code_a_high_count,
  (SELECT COUNT(*) FROM table_one WHERE date=myDate AND name=myName AND CODE_B BETWEEN 100 AND 199) AS code_b_low_count,
  (SELECT COUNT(*) FROM table_one WHERE date=myDate AND name=myName AND CODE_B BETWEEN 200 AND 299) AS code_b_high_count,
  (SELECT COUNT(*) FROM table_one WHERE date=myDate AND name=myName AND CODE_C BETWEEN 100 AND 199) AS code_c_count
FROM table_one
WHERE ROWNUM=1


texts:
I'm trying to separate logic from the controller, so I created this Upload class. It is not a big class, just a class so that the controller doesn't know about the logic and stuff like that.

<?php
namespace Dnianas\Uploads;

class Photo
{

    /**
     * The image filename.
     * @var string
     */
    protected $filename;

    /**
     * The image extension.
     * @var string
     */
    protected $extension;

    /**
     * The image hashed value that we hashed using SHA1.
     * @var string
     */
    protected $hashedName;

    /**
     * The filename with the hashed name and the extension.
     * @var string
     */
    public $path;

    public function makeProfilePicture($input)
    {
        $this->fileName     = $input->getClientOriginalName();
        $this->extension    = $input->getClientOriginalExtension();
        $this->hashedName   = sha1(time() . $this->fileName);
        $this->path         = $this->hashedName . '.' .$this->extension;

        // Resize the image
        $image = \Image::make($input);
        $image->fit(300, 300);

        // Set the destination
        $destination = photos_path() . '/' . $this->path;

        // Save the image
        $image->save($destination);

        // Return the object
        return $this;
    }

    public function makeCoverPhoto($input)
    {
        $this->fileName     = $input->getClientOriginalName();
        $this->extension    = $input->getClientOriginalExtension();
        $this->hashedName   = sha1(time() . $this->fileName);
        $this->path         = $this->hashedName . '.' .$this->extension;

        // Resize the image
        $image = \Image::make($input);
        $image->fit(900, 350);

        // Set the destination
        $destination = photos_path() . '/cover-' . $this->path;

        // Save the image
        $image->save($destination);

        return $this;
    }

}

As you can see, the first 4 lines from each method is exactly the same. How can I improve this?

EDIT: I've followed the constructor method. I added the constructor.

Here is the final class:

<?php
namespace Dnianas\Uploads;

use Symfony\Component\HttpFoundation\File\UploadedFile;

class Photo
{

    /**
     * The image filename.
     * @var string
     */
    protected $filename;

    /**
     * The image extension.
     * @var string
     */
    protected $extension;

    /**
     * The image hashed value that we hashed using SHA1.
     * @var string
     */
    protected $hashedName;

    /**
     * The filename with the hashed name and the extension.
     * @var string
     */
    public $path;

    /**
     * The input from the user, Usually it's the file.
     * @var object
     */
    public $input;

    public function __construct(UploadedFile $input)
    {
        $this->input        = $input;
        $this->fileName     = $this->input->getClientOriginalName();
        $this->extension    = $this->input->getClientOriginalExtension();
        $this->hashedName   = sha1(time() . $this->fileName);
        $this->path         = $this->hashedName . '.' .$this->extension;
    }

    public function makeProfilePicture()
    {
        // Resize the image
        $image = \Image::make($this->input);
        $image->fit(300, 300);

        // Set the destination
        $destination = photos_path() . '/' . $this->path;

        // Save the image
        $image->save($destination);

        // Return the object
        return $this;
    }

    public function makeCoverPhoto()
    {
        // Resize the image
        $image = \Image::make($this->input);
        $image->fit(900, 350);

        // Set the destination
        $destination = photos_path() . '/cover-' . $this->path;

        // Save the image
        $image->save($destination);

        return $this;
    }

}

And in the controllers I do this:

$profilePicture = (new Photo($input))->makeProfilePicture();


texts:
I have made a linear interpolation functions as a side project of mine. It assumes everything is sorted before hand - x and f(x) are the same length.

I would like to ask for:

general recommendations
if I can improve the design (generalize it to all iterables like std::array etc...)
and for further performance optimizations.

#include <algorithm>
#include <cmath>
#include <type_traits>
#include <vector>

#if (__cplusplus < 202002L)
template <typename T,
          typename = std::enable_if_t<std::is_floating_point<T>::value>>
T lerp(T a, T b, T t) noexcept {
  return a + t * (b - a);
}
#else
using std::lerp;
#endif

template <typename T,
          typename = std::enable_if_t<std::is_floating_point<T>::value>>
class ListLerp {
 public:
  explicit ListLerp(const std::vector<T>& xp, const std::vector<T>& yp)
      : xp(xp), yp(yp) {
    b = this->xp.begin() + 1;
  }

  [[nodiscard]] T interp(const T x) noexcept {
    // No extrapolation
    if (x <= xp.front()) return yp.front();
    if (x >= xp.back()) return yp.back();

    // b = xp.begin() + 1;

    // find b position
    while (x > *b) b++;

    // Calculate a, a_y, b_y from b
    const auto a = b - 1;
    const auto a_y = yp.begin() + (a - xp.begin());
    const auto b_y = yp.begin() + (b - xp.begin());

    const auto t = (x - *a) / (*b - *a);

    return lerp(*a_y, *b_y, t);
  };

 private:
  typename std::vector<T>::const_iterator b;
  const std::vector<T>& xp;
  const std::vector<T>& yp;
};

template <typename T,
          typename = std::enable_if_t<std::is_floating_point<T>::value>>
std::vector<T> interp(const std::vector<T>& xp, const std::vector<T>& yp,
                      const std::vector<T>& x) {
  std::vector<T> out(x.size());

  auto lLerp = ListLerp(xp, yp);

  std::transform(x.begin(), x.end(), out.begin(),
                 [&lLerp](const auto& xi) { return lLerp.interp(xi); });

  return out;
}

///////////////
int main() {
  std::vector<double> xp = {1, 2, 3};
  std::vector<double> fp = {3, 2, 0};

  for (auto &i : interp(xp, fp, {1, 1.5, 2.72})){
    std::cout << " " << i;
  }
  std::cout << "\n";

}


texts: Options with a "yes" or "no" radio button

texts:
I have about 6 of these, but I'm only posting two. Essentially I have a bunch of options with a "yes" or "no" radio button. If "no" is selected, I want a form to popup.

$('#Option1').live('change', function() {
    if ($('input[name=Option1]:checked').val() == "False") {
        $('#formDiv').show();
    } else {
        $('#formDiv').hide();
    }
});
$('#Option2').live('change', function() {
    if ($('input[name=Option2]:checked').val() == "False") {
        $('#formDiv').show();
    } else {
        $('#formDiv').hide();
    }
});

How can I make this more efficient, or even consolidate it? Or is having a function for each pair of radio buttons necessary?


texts: Find all instances of a given weekday in February for a given year

texts:
A friend of mine was practicing his programming skills with a textbook meant to prepare students for computer science exams. He asked for help with a specific task.

The task is to capture user input (day of week and a year in the range 1500 to 2005 inclusive), and output all instances of the weekday in February that year.

The differences between the Julian and Gregorian calendars are to be accounted for.

Now, most likely the idea behind this task was to have the student create an algorithm to manually calculate the dates. However, as Java SE seems to be allowed in exams in my country, I came up with the idea of utilizing the GregorianCalendar class (which, despite its name, combines the Julian and Gregorian calendars).

package calendar;

import java.text.DateFormat;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Scanner;

public class CalendarTask {
    public static void main(String[] args) {
        GregorianCalendar cal = new GregorianCalendar();

        HashMap<String, Integer> daysOfWeek = new HashMap<>();
        daysOfWeek.put("monday", cal.MONDAY);
        daysOfWeek.put("tuesday", cal.TUESDAY);
        daysOfWeek.put("wednesday", cal.WEDNESDAY);
        daysOfWeek.put("thursday", cal.THURSDAY);
        daysOfWeek.put("friday", cal.FRIDAY);
        daysOfWeek.put("saturday", cal.SATURDAY);
        daysOfWeek.put("sunday", cal.SUNDAY);

        System.out.print("Enter day of week: ");
        Scanner sc = new Scanner(System.in);
        int dayOfWeek, year;
        try {
            dayOfWeek = daysOfWeek.get(sc.next().toLowerCase());
            System.out.print("Enter year (1500-2005 inclusive): ");
            year = Integer.parseInt(sc.next());
            if (year < 1500 || year > 2005) throw new Exception();

            System.out.println("Output:");
            DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.GERMANY);
            cal.set(cal.YEAR, year);
            trySetDay(cal, dayOfWeek, 1);
            do {
                System.out.println(df.format(cal.getTime()));
                cal.add(cal.DAY_OF_MONTH, 7);
            } while (cal.get(cal.MONTH) == cal.FEBRUARY);
        } catch (Exception e) {
            System.out.println("Incorrect input!");
        } finally {
            sc.close();
        }
    }

    private static void trySetDay(GregorianCalendar cal, int dayOfWeek, int weekOffset) {
        cal.set(cal.MONTH, cal.FEBRUARY);
        cal.set(cal.WEEK_OF_MONTH, weekOffset);
        cal.set(cal.DAY_OF_WEEK, dayOfWeek);
        if (cal.get(cal.MONTH) != cal.FEBRUARY) trySetDay(cal, dayOfWeek, weekOffset + 1);
    }
}

Example input and output (dates are output in DD.MM.YYYY format):

Enter day of week: Monday
Enter year (1500-2005 inclusive): 2000
Output:
07.02.2000
14.02.2000
21.02.2000
28.02.2000

The trySetDay() method is meant for cases when the attempted day belongs to the previous month. In such a case, the week offset is increased by one to make sure we're dealing with February.

This code works fine and I'm satisfied with it. The catch is there to handle NullPointerException (when attempting to assign null, a possible result of HashMap.get(), and also when parsing the year) and a generic Exception set to limit the possible input to the range 1500 to 2005.

What can be improved about this code? Is there anything that caught your eye instantly and that could be done better? Any and all feedback is appreciated.
Also, is it a good idea to access static class members via an instance of the class? Such as cal.MONDAY (where cal is an instance of GregorianCalendar), instead of GregorianCalendar.MONDAY?


texts:
I have posed another question here and I am writing this one for some code review:
class ConfigFile
{
private:
  PTree m_ptConfig;

public:
  ConfigFile(const std::string& name)
  {
    json::read_json(name, m_ptConfig);
  }

  ~ConfigFile();

  double getVal1()
  {
    std::string path = "path.to.val1";
    double val1 = m_ptConfig.get<double>(path, -1);

    if (val1 < 0)
    {
      std::string msg = "getVal1() failed or val1 < 0";
      throw MyConfigFileException(msg);
    }

    return val1;
  }
  double getVal2() {/*the same as before*/};
  // ... more values the same way
};

The exception class is here:
class MyConfigFileException : public MyIOException // MyIOException is derived from std::exception
{
private:
  std::string m_msg;

public:
  MyConfigFileException(const std::string msg) : msg(msg) {}
  virtual const char* what() const throw()
  {
    return m_msg.c_str();
  }
};

The handling for this kind of exception I have done it in main function:
int main(int argc, char **argv)
{
  const std::string configFileName = argv[1];
  try
  {
    RunAlgo algo(configFileName);
    algo.runAlgorithm();
  }
  catch (MyConfigFileException& mcfe)
  {
    std::cout << "Config File Exception: " << mcfe.what() << std::endl;
    return -1;
  }
  catch (MyIOException& mioe)
  {
    std::cout << "IOException: " << mioe.what() << std::endl;
    return -2;
  }
  catch (std::exception& e)
  {
    std::cout << "Unknown exception: " << e.what() << std::endl;
    return -3;
  }

  return 0;
}

I use the chatch blocks to see if it has crashed because of me or not, that is why I just print the message and return a value. (Maybe this is not necessary since it returns a different value, but I let it there for the moment)
In the runAlgorithm() function I have a loop, where I treat another kind of exceptions:
// ...
void RunAlgo::runAlgorithm()
{
  ConfigFile cf("config.json")
  double v1 = cf.getVal1();
  // ...
  for (int i = 0; i < 100; i++)
  {
    // ...
    try
    {
      foo(cf);
    }
    catch (MyOtherExceptions & moe)
    {
      std::cout << moe.what() << std::endl;
    }
    // ...
  }
  // ...
}

MyOtherExceptions are going to be treated separately, like: for the current iteration, there is a problem with a buffer, send a message to a queue.
foo is implemented here:
void foo(const ConfigFile& cf)
{
  double v2 = cf.getVal2();

  // some other code that may throw MyOtherException exceptions
}

Do you think I am using the exceptions correctly?

I admit that the handling is not really done, but I am asking if I am doing right with the throws and try-catch blocks, supposing that instead of just printing messages the handling is done (as "sending message to a queue").


texts: Calculate how many coins, coin values are 50, 20, 10 and 5

texts:
The code should enter an integer between 5-95 and calculate how many coins, coin values are 50, 20, 10 and 5.

My concern is the CalcChange function and whether that is acceptable C code.

#include <stdio.h>

#define TRUE 1
#define FALSE 0

void GetNum(int &amount)
{
        printf("Enter an integer between 5 and 95 inclusive:\n");
        scanf("%d%*c", &amount);

        return;
}

int Verify(int amount)
{
        if(amount <= 4 || amount >= 95)
                return FALSE;

        return(TRUE);
}

//Function calculates number of coins for each denomination
//and returns the remainder as the new value of amount
//until remainder is <= 4

int CalcChange(int &amount, int denomination)
{

        int change = amount / denomination;

        amount = amount % denomination;

        return(change);

}

//Instead of wasting the remainder, lets donate it to charity
void PrintResult(int fifty, int twenty, int ten, int five, int remainder)
{
        printf("\n%d 50c coins\n%d 20c coins\n%d 10c coins\n%d 5c coins.\n", fifty, twenty, ten, five);
        printf("\nThe remainder of %d cents will be donated to charity.\n", remainder);

        return;
}

int main()
{
        int a, change, fifty, twenty, ten, five, remainder;

        GetNum(a);

        Verify(a);

        if(Verify(a))
        {
                fifty = CalcChange(a, 50);
                twenty = CalcChange(a, 20);
                ten = CalcChange(a, 10);
                five = CalcChange(a, 5);
                remainder = CalcChange(a, 1);

                PrintResult(fifty, twenty, ten, five, remainder);
        }
        else
        {
                printf("\n%d is out of range!\n", a);
        }

        return(0);
}


texts: Putting as many ships on a square board as possible

texts:
Github repository
Origanally I wrote a program that let you play battleship against the computer.
Pretty easy:

create a number of ships
generate random cells for all the ships
let the user try to guess

I implemented a way to place as many ships as possible:
If I have a 3x3 board and I want to place 4 ships that are 2 cells long, there are only few placements that allow the maximum number of ships in the board.
Example correct placement:
|1|1|O|
|2|2|4|
|3|3|4|

Example wrong placement:
|0|1|1|
|2|2|0|
|0|3|3|

Code(full code on github):
public void prepareGame(){

    if (!(field_size*field_size/ship_length >= ship_numbers)){
        System.out.println("Error: Game numbers are invalid");
        System.exit(0);
    }

    for (int i = 0; i < ship_numbers; i++) {
        Ships.add(new Ship();
    }

    ArrayList<String> toTest;
    int leftToPlace = ship_numbers;

    for (Ship ship : Ships){
        System.out.println("generating cells for "+ship);

        while(true){

            toTest = generateCells();

            if (!checkShips(toTest)){

                if(backtrackShips(toTest, leftToPlace)){
                    ship.setShip(toTest);
                    System.out.println("success for "+ship+" "+toTest);
                    System.out.println();
                    leftToPlace--;
                    break;
                }
            }
        }
    }
}

private boolean backtrackShips(ArrayList<String> toBacktrack, int shipsToPlace){

    boolean backtrack_result = false;
    ArrayList<String> cells;
    ArrayList<ArrayList<String>> givenCells = new ArrayList<>();

    for (int i = 0; i < (ship_numbers - shipsToPlace); i++) {
        givenCells.add(Ships.get(i).getCells());
    }

    //System.out.println("backtracking: "+toBacktrack);
    //System.out.println("given cells before backtrack: "+ givenCells);
    givenCells.add(toBacktrack);
    shipsToPlace--;

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

        for (int j = 0; j < 1000; j++) {

            cells = generateCells();

            // check if cells lap over already chosen cells
            for (ArrayList<String> list : givenCells) {

                if (Collections.disjoint(list, cells)) {
                    backtrack_result = true;

                } else if (!Collections.disjoint(list, cells)) {
                    backtrack_result = false;
                    break;
                }
            }

            if(backtrack_result) {
                givenCells.add(cells);
                break;
            }
        }
    }

    if (shipsToPlace == 0) { //base-case
        backtrack_result = true;
    }

    //System.out.println("given cells after backtrack: "+ givenCells);
    return backtrack_result;
}

public boolean checkShips(ArrayList<String> cells){

    boolean result = false;

    for (Ship ship : Ships){

        if (!Collections.disjoint(cells, ship.getCells())){
            result = true;
        }
    }
    return result;
}

If you want to know the Ship Class:
package src;

import java.util.ArrayList;

public class Ship {

ArrayList<String> cells = new ArrayList<>();

public void setShip(ArrayList<String> cells){
    this.cells = cells;
}

public ArrayList<String> getCells(){
    return this.cells;
}

public String checkYourself(String stringTip){

    String result = "Miss";

    if (this.cells.contains(stringTip)){
        result = "Hit";

        this.cells.remove(stringTip);
    }

    if (this.cells.isEmpty()) {
        result = "submerged";
    }
    return result;
}
}

I have basically two questions.
Is this backtracking?
Where can I optimize the code?
Edit: changed naming of ships.


texts:
I've recently solved the famous N-Queens problem:

  Can you place \$N\$ chess queens on a \$N × N\$ board in such a way that no one
  attacks another queen?

The idea here is based on the ideas from several blogposts describing a bitwise approach - approaching the board row by row, keeping track of bits of 3 numbers - columns, major and minor diagonals:

class Solution(object):
    def totalNQueens(self, n):
        all_ones = 2 ** n - 1

        def helper(ld, column, rd, count=0):
            if column == all_ones:  # filled out all vacant positions
                return 1

            possible_slots = ~(ld | column | rd)  # mark possible vacant slots as 1s
            while possible_slots & all_ones:
                current_bit = possible_slots & -possible_slots  # get first 1 from the right
                possible_slots -= current_bit  # occupy a slot

                # mark conflicts in the next row
                next_column_bit = column | current_bit
                next_rd_bit = (rd | current_bit) << 1
                next_ld_bit = (ld | current_bit) >> 1

                count += helper(next_ld_bit, next_column_bit, next_rd_bit)
            return count

        return helper(0, 0, 0)

The solution was accepted by the LeetCode OJ and actually beats 98.97% of Python solutions. But, can we optimize it even further? What would you improve code-quality/readability wise?

Another follow-up concern is that I don't see an easy way for this problem to instead of counting possible board arrangements, collect all possible distinct board configurations.


texts: Comparing dates with SharePoint PnP PowerShell

texts:
I am wondering if should change my if statement that compares two dates if they are equal. Is there a better way of doing this operation? The code does what it supposed to do. No errors. The Code:

if((Get-date).ToString("yyy-MM-dd") -eq $ListItem["Aviseringsdatum"].ToLocalTime().ToString("yyy-MM-dd")){
Write-Output "True"
}


texts: Hackerrank: Count the number of palindromes in a given string

texts:
I am solving a problem for Hackerrank where I have to count the number of palindromes in a given string.
I have the following code which counts the number of palindromes accurately but times out for large strings. How do I make the code more time-efficient?
def countPalindromes(s):
    num_palindrome = 0

    for i in range(len(s)):
        for j in range(i + 1, len(s) + 1):
            substring = s[i: j]
            if len(substring) == 1:
                num_palindrome += 1
            else:
                for idx in range(len(substring)):
                    if substring[idx] != substring[-idx-1]:
                        num_palindrome -= 1
                        break
                num_palindrome += 1

    return num_palindrome


texts: Decreasing complexity of loop & Find- VBA

texts:
I have written the following code; both Sheet 1 and Sheet 2 are rather big sheet with lots of data. Run this Macro is extremely time comsuming ( It has a high complexity I guess). I'm quite new at VBA and therefore having trouble make the code more effective.

Sub Find()

    Dim rgFound As Range
    Dim Index As Long: Index = 6
    Dim Row as Long

    Do While Worksheets("Sheet2").Cells(Index, "D").Value > 0

         Sheets("Sheet1").Select
         Set rgFound = Range("A1:A20000").Find(Worksheets("Sheet2").Cells(Index, "D").Value)

         If Not rgFound Is Nothing Then

            Row = rgFound.Row

            Worksheets("Sheet1").Range("E" & Row).Value = Worksheets("Sheet2").Range("AA" & Index).Value
            Worksheets("Sheet1").Range("F" & Row).Value = Worksheets("Sheet2").Range("AB" & Index).Value
            Worksheets("Sheet1").Range("G" & Row).Value = Worksheets("Sheet2").Range("AC" & Index).Value
            Worksheets("Sheet1").Range("H" & Row).Value = Worksheets("Sheet2").Range("Z" & Index).Value
            Worksheets("Sheet1").Range("J" & Row).Value = Worksheets("Sheet2").Range("AG" & Index).Value
            Worksheets("Sheet1").Range("I" & Row).Value = Worksheets("Sheet2").Range("AD" & Index).Value

        Else
            ' Function // Not done yet
        End If

    Index = Index + 1
    Loop
End Sub

Is the built in Find function effective? The loop loops trough roughly 250-400 values.

Basically, Sheet 2 refers to a specific month. Sheet one contians 12 rows for each employee ( one for each month ). Each Sheet (Sheet2-Sheet13) Have exactly the same format. The values copied from these sheets to Sheet1 are salary, days worked and so forth.


texts: Get length of the longest sequence of numbers with the same sign

texts:
I need to get length of the longest sequence of numbers with the same sign. Assumes that zero is positive. For example:

{10, 1, 4, 0, -7, 2, -8, 4, -2, 0} → 4
{0, 1, 2, 3, -2, -4, 0}  → 4
{1, -2, 0, -1} → 1

I wrote a function:

unsigned getLongestSameSignSequenceLength(std::vector<int> const& a)
{
    unsigned maxlen = 1;

/* Assumes that zero is positive. */
#define SIGN(a) (a >= 0)

    for (size_t i = 1, len = 1; i < a.size(); i++, len++) {
        if (SIGN(a[i]) != SIGN(a[i - 1])) {
            maxlen = std::max(maxlen, len);
            len = 0;
        } else {
            if (i == a.size() - 1)
                return std::max(maxlen, len + 1);
        }
    }

#undef SIGN

    return maxlen;
}

Can you please give me tips to improve my code?


texts: Does this nodeunit test conform to best practices?

texts:
I have inherited a node-js project, and I am completely new to it. Fortunately, it is already covered by unit tests.

The class under test, FmsRescuers, has the responsibility of sending HTTP requests to a remote server.

My first refactoring was to extract the HTTP behavior into the HttpRequest class, to allow testing that an operation requests the correct url with the correct data, without actually performing the http request. The HttpRequest class did not previously exist.

I am looking for feedback on the unit test from a perspective of best practices. In particular, how do I best avoid the duplication of calling the checkIn function through the different tests?

require('../server/extensions');
var FmsRescuers = require('../server/fms_rescuers');
var Rescuer = require('./stubs/helper').Rescuer;

var requestedPath;
var requestedStationNumber;
var requestedRescuerNumber;
var httpRequest = {
    post: function(path, requestData, callback) {
              requestedPath = path;
              requestedStationNumber = requestData.stationNumber;
              requestedRescuerNumber = requestData.rescuerNumber;
              callback('', 200);
          }
};
var rescuers = new FmsRescuers(httpRequest);
var rescuer = new Rescuer(42, 'Name', new Date().addHours(-2).toTimeZonedString(), new Date().addHours(-1).toTimeZonedString());

exports.testCheckIn = {
    setUp: function(callback) {
               requestedPath = undefined;
               requestedStationNumber = undefined;
               requestedRescuerNumber = undefined;
               callback();
           },
    'check in requests correct path' : function(test) {
        rescuers.checkIn(rescuer, 123, 3, function(result, status) {
            test.equal(requestedPath, '/attendance/checkin');
            test.done();
        });
    },

    'check in sends correct station number' : function(test) {
        rescuers.checkIn(rescuer, 123, 3, function(result, status) {
            test.equal(requestedStationNumber, 123);
            test.done();
        });
    },

    'check in sends correct rescuer number' : function(test) {
        rescuers.checkIn(rescuer, 123, 3, function(result, status) {
            test.equal(requestedRescuerNumber, 42);
            test.done();
        });
    }
};


texts: Use of external memory or a custom allocator

texts:
I'm creating a class which uses a custom buffer. I want to offer the possibility to pass an external memory address (for higher interoperability between languages) or (for convenience) to specify a custom allocator type. The following code outlines what I mean:

template<typename int_type, class alloc = void>
class uses_custom_buffers
    : uses_custom_buffers<int_type, void>
{
public:
    uses_custom_buffers<int_type, alloc>* set_buffer(std::size_t count, std::size_t size)
    {
        typename alloc::rebind<int_type*>::other pointer_alloc;
        int_type** buffer = pointer_alloc.allocate(count);
        for (std::size_t i = 0; i < count; ++i)
            buffer[i] = this->m_alloc.allocate(size);
        this->uses_custom_buffers<int_type, void>::set_buffer(count, buffer, size);
        return this;
    }

private:
    using uses_custom_buffers<int_type, void>::set_buffer;

    alloc m_alloc;
};

template<typename int_type>
class uses_custom_buffers<int_type, void>
{
public:
    uses_custom_buffers<int_type, void>* set_buffer(std::size_t count, int_type** buffers, std::size_t size)
    {
        this->m_buf   = buffers;
        this->m_count = count;
        this->m_size  = size;
        return this;
    }

private:
    int_type**  m_buf;
    std::size_t m_count,
                m_size;
};

Please note: This example doesn't care about deallocating any resource or exception safeness (to simplify matters).
Do you see any kind of problems with that design?


texts: Making a list from user input - follow-up

texts:
I have made the changes that people have suggested from my previous question.  I want to try and make it even tidier if possible.  What can I change to make it more optimized? My imports are quite messy and I am not sure what ones I actually need, so if you can help with that, please do.

#Imports
import tkinter
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename
from tkinter.messagebox import showerror
from tkinter import filedialog
import sys

class MyFileManager(object):
    def __init__(self, filename='', save_filename=''):
        self.filename = filename
        self.save_filename = save_filename

    def save_users_list(self, list_name):
        with open(self.filename, 'r') as file:
            users_list = [line.strip() for line in file.readlines()]

        with open(self.save_filename, 'w') as file:
            file.write('{} = {}'.format(list_name, str(users_list)))

    def get_filename(self):
        self.filename = askopenfilename(filetypes=(("Text files", "*.txt"),
                                                        ("All files", "*.*")))

    def get_save_file(self):
        self.save_filename = asksaveasfilename(filetypes=(("Text files", "*.txt"),
                                                          ("All files", "*.*")))

manager = MyFileManager()

#Window
window = tkinter.Tk()
window.title("Python List Maker")
window.geometry("300x170")

#Label
file_select_label = tkinter.Label(window, text="Please select your file:")
file_select_label.pack()

#Button
filename_button = tkinter.Button(window, text="Browse", command=manager.get_filename)
filename_button.pack()

#List Name
list_name_label = tkinter.Label(window,text="Please enter what you want to call the list:")
list_name_label.pack()
list_name = Entry(window)
list_name.pack()

#Save List
save_list_label = tkinter.Label(window,text="Please select where you want to save the list:")
save_list_label.pack()
save_filename_button = tkinter.Button(window, text="Browse", command=manager.get_save_file)
save_filename_button.pack()

#Go
go_button = tkinter.Button(window, text="Go!", command=lambda: manager.save_users_list(
                                                                    list_name.get()))
go_button.pack()

#Main Loop
window.mainloop()


texts: Python script which fetches Amazon product details using its API

texts:
This is a script which takes an Amazon URL as input, takes out ASIN/ISBN from the URL, and uses Amazon Python API to fetch details.

For this task, I looked at many Amazon URLs and observed the following things:

ASIN/ISBN is always present in an Amazon URL
ASIN/ISBN can be present anywhere in the URL
ASIN is always in capital letters, consists of alphabets and numbers only and length is always 10
If ASIN is not present then it's a link to a book on Amazon and ISBN will be present
ISBN consists only of numbers
Amazon uses ISBN-10 format i.e. length of ISBN is 10
Haven't come across ASIN which is purely numbers and without any alphabets
ASIN or ISBN, always followed by '/'

I hope I covered everything, but if I missed some case, please let me know.

Secondly, I care about only Amazon India. So it throws that ASIN is invalid if I give an ASIN of Amazon US or any other country, or gives pricing info zero. I don't know why it is causing such behaviour (example).

Flow: Get the URL, check for either ASIN or ISBN, if none are present return false else use API to fetch name, price, URL and product image.

import re
from amazon.api import AmazonAPI

AMAZON_ACCESS_KEY = 'AKI...JP2'
AMAZON_SECRET_KEY = 'Eto...uxV'
AMAZON_ASSOC_TAG = 'p...1'

asin_regex = r'/([A-Z0-9]{10})'
isbn_regex = r'/([0-9]{10})'

def get_amazon_item_id(url):
    # return either ASIN or ISBN
    asin_search = re.search(asin_regex, url)
    isbn_search = re.search(isbn_regex, url)
    if asin_search:
        return asin_search.group(1)
    elif isbn_search:
        return isbn_search.group(1)
    else:
        # log this URL
        return None

def get_amazon_product_meta(url):
    # the input URL is always of amazon
    amazon = AmazonAPI(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY, AMAZON_ASSOC_TAG, region="IN")

    item_id = get_amazon_item_id(url)
    if not item_id:
        return None

    try:
        product = amazon.lookup(ItemId=item_id)
    except amazon.api.AsinNotFound:
        # log this ASIN
        return None

    # product.price_and_currency returns in the form (price, currency)
    product_price = product.price_and_currency[0]

    if product_price:
        return product.offer_url, product.title, product.large_image_url, product_price
    return None


texts: Using TinyMCE with responsive file manager PHP and Javascript

texts:
I use TinyMCE with responsivefilemanager and I wanted to know that is my code well-written maintainable and readable, Sorry If this sounds like a stupid and basic question because this is such a basic thing to do, and I have also been in web dev for a long time but I am new at WYSIWYG editors and TinyMCE.
Here is my file structure
Website's main parent folder/public_html
    myapp folder for the whole app
      my HTML & some PHP files which use TinyMCE and responsivefilemanager
      my tinyMCE's init.js file
      plugins folder for all my 3rd party plugins
        TinyMCE folder which contains TinyMCE itself
          other folders you find inside TinyMCE
          a plugins folder inside TinyMCE used for plugins related to it
            filemanager folder for the responsivefilemanager plugin

Here is my necessary code of config.php file which is inside the filemanager's config folder
<?php

    /*
        |--------------------------------------------------------------------------
        | DON'T TOUCH (base url (only domain) of site).
        |--------------------------------------------------------------------------
        |
        | without final / (DON'T TOUCH)
        |
        */
        'base_url' => ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http"). "://". @$_SERVER['HTTP_HOST'],
        /*
        |--------------------------------------------------------------------------
        | path from base_url to base of upload folder
        |--------------------------------------------------------------------------
        |
        | with start and final /
        |
        */
        'upload_dir' => '/myapp/uploads/',
        /*
        |--------------------------------------------------------------------------
        | relative path from filemanager folder to upload folder
        |--------------------------------------------------------------------------
        |
        | with final /
        |
        */
        'current_path' => '../../uploads/',

        /*
        |--------------------------------------------------------------------------
        | relative path from filemanager folder to thumbs folder
        |--------------------------------------------------------------------------
        |
        | with final /
        | DO NOT put inside upload folder
        |
        */
        'thumbs_base_path' => '../../thumb/',
?>

My init.js file so I can initialize TinyMCE for my textarea
         tinymce.init({
            selector: "textarea",
            plugins: [
                "advlist autolink link image lists charmap print preview hr anchor pagebreak",
                "searchreplace wordcount visualblocks visualchars insertdatetime media nonbreaking",
                "table contextmenu directionality emoticons paste textcolor responsivefilemanager code codesample"
            ],
            toolbar1: "undo redo | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | styleselect",
            toolbar2: "| responsivefilemanager | link unlink anchor | image media | codesample | forecolor backcolor  | print preview code ",
            image_advtab: true,
            branding: false,

            external_filemanager_path: "plugins/filemanager/",
            filemanager_title: "Scintilla Filemanager for Lessons",
            external_plugins: {
                "filemanager": "plugins/filemanager/plugin.min.js"
            }
        });

        tinymce.init(demoBaseConfig);


texts:
I have a simple Model class that represents a calculator.

Header file:

@class MMCalculator;

@protocol MMCalculatorDelegate <NSObject>

@required - (void)mmCalculator:(MMCalculator *)mmCalulatorFinishedCalculatingValues;

@end

@interface MMCalculator : NSObject

@property (nonatomic, weak) id <MMCalculatorDelegate> delegate;
@property float calculatedPay;
@property float calculatedSavingsForStuff;
@property float calculatedSavingsForProfitFormula;
@property float calculatedSavingsForTaxes;

- (void)calculateValuesWithMonthlyRevenue:(float)monthlyRevenue;
- (float)calculateYourPay:(float)monthlyRevenue;
- (float)calculateSavingsForStuff:(float)monthlyRevenue;
- (float)calculateSavingsForProfitFormula:(float)monthlyRevenue;
- (float)calculateSavingsForTaxes:(float)monthlyRevenue;

@end

Implementation file:

#import "MMCalculator.h"

#pragma mark - Static Variables
static float const percentageToPayYourself = 0.50f;
static float const percentageToSaveForStuff = 0.20f;
static float const percentageToSaveForProfitFormula = 0.20f;
static float const percentageToSaveForTaxes = 0.10f;

@implementation MMCalculator

#pragma mark - Calculator Methods
- (void)calculateValuesWithMonthlyRevenue:(float)monthlyRevenue
{
    //Call all 4 calculation methods and set calculated properties
    self.calculatedPay = [self calculateYourPay:monthlyRevenue];
    self.calculatedSavingsForStuff = [self calculateSavingsForStuff:monthlyRevenue];
    self.calculatedSavingsForProfitFormula = [self calculateSavingsForProfitFormula:monthlyRevenue];
    self.calculatedSavingsForTaxes = [self calculateSavingsForTaxes:monthlyRevenue];

    //Call delegate method
    [self.delegate mmCalculator:self];
}
- (float)calculateYourPay:(float)monthlyRevenue
{
    return percentageToPayYourself * monthlyRevenue;
}

- (float)calculateSavingsForStuff:(float)monthlyRevenue
{
    return percentageToSaveForStuff * monthlyRevenue;;
}

- (float)calculateSavingsForProfitFormula:(float)monthlyRevenue
{
    return percentageToSaveForProfitFormula * monthlyRevenue;
}

- (float)calculateSavingsForTaxes:(float)monthlyRevenue
{
    return percentageToSaveForTaxes * monthlyRevenue;
}

@end

Here are the key things I am looking for feedback on:

Right now I store the class's calculated values in public properties so they can be accessed by other classes. Should it be the class's responsibility to store these calculated values in it's properties, or should it be the responsibility of the class that is calling this class's methods?.
Did I define my static variables correctly? Are they following best practices?
What do you think of the class's delegate method?
Am I following best practices by using floats to represent money? I have a feeling that I should be using something else.


texts:
I wrote a method that will return the minimum element in a linked-list that operates in O(1) time. I tested and everything works fine. However, I was wondering if there is anything that I can do to make my code more efficient or cleaner.

public class Node {

    //private Object item;
    Node next;
    Object item;

    // constructor
    public Node(Object item) {
        this.item = item;
        next = null;
    }

}

public class MinElementInStack {

    static Node stack;
    static Node minStack;

    public void push(int data) {

        // push nodes into stack
        Node last = new Node(data);
        last.next = stack;
        stack = last;

        // check if node being pushed is new min
        // if it is then push into minStack
        if(minStack == null) { // for first node
            Node toBePushed = new Node(data);
            toBePushed.next = minStack;
            minStack = toBePushed;
        } else { // if int to be pushed is less than current min on stack
                // then push it onto the stack, otherwise push the same min value from previous
            int toBePushedInt = data;
            if(toBePushedInt < (Integer)minStack.item) {
                Node toBePushed = new Node(data);
                toBePushed.next = minStack;
                minStack = toBePushed;
            } else {
                Node toBePushed = new Node((Integer)minStack.item);
                toBePushed.next = minStack;
                minStack = toBePushed;
            }
        }

    }

    public void pop() {
        if (stack != null && minStack != null) {
            stack = stack.next;
            minStack = minStack.next;
        }
    }

    public int min() {

        int min = (int) minStack.item;
        return min;

    }

    public void print(Node node) {
        Node temp = node;
        while (temp != null) {
            System.out.println(temp.item);
            temp = temp.next;
        }
    }

    public static void main(String[] args) {

        MinElementInStack s = new MinElementInStack();

        s.push(5);
        s.push(-28);
        s.push(8);
        s.push(-50);
        s.push(-4);
        s.push(-38);
        s.push(100);

        System.out.println("Original Stack: ");
        s.print(stack);
        System.out.println();
        System.out.println("Min Stack: ");
        s.print(minStack);
        System.out.println();
        System.out.println("Minimum element in current stack: " + s.min());
    }

}


texts: Which loop to use for multiple if statements which serialize objects

texts:
I have figured out how to serialize multiple objects, however I am utterly convinced I can use some kind of loop for the if statements below, to avoid duplication. Please can someone advise how I would do this?

I have 20 objects in total, this code snippet shows the "if statements" for 4 of them.

import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.*;
import java.util.Arrays;

public class Serializer extends WriteClub
{
   public void Serialize()
   {

    MainMenu pass_choice = new MainMenu();
    int passed_choice = pass_choice.chooseTeam();

    if(passed_choice==1){
    ClubInfo club = new ClubInfo("Arsneal" , "Emirates" , "Premier League" , 11122333 , 60000);
    tryWriteClub(club);
    } // end if 1

    if(passed_choice==2){
    ClubInfo club1 = new ClubInfo("Aston Villa" , "Villa Park" , "Premier League" , 111223334 , 40000);
    tryWriteClub(club1);
    } // end if 2

    if(passed_choice==3){
    ClubInfo club2 = new ClubInfo("Bournemouth" , "Dean Court" , "Premier League" , 111223335 , 20000);
    tryWriteClub(club2);
    } // end if 3

    if(passed_choice==4){
    ClubInfo club3 = new ClubInfo("Chelsea" , "Stamford Bridge" , "Premier League" , 111223336 , 50000);
    tryWriteClub(club3);
    } // end if 2
   }
}


texts:
This class uses the openweathermap API to receive information about the current weather and forecasts. I am looking for any type of advice, but primary for structure and style improvement suggestions:
This method builds the the API URL:

private Uri BuildQueryURL(Interval requestType, NameValueCollection parameters)
{
    if (parameters == null) parameters = new NameValueCollection();
    string relativePath = "";
    //set query//
    switch (requestType)
    {
        case Interval.Current:
            relativePath = "weather";
            break;
        case Interval.Forecast:
            relativePath = "forecast";
            break;
    }
    //add api key//
    parameters.Add("APPID", ApiKey);
    //if needed, add unit parameter//
    if (Units != Units.Default) parameters.Add("units", Units.ToString());
    //build uri
    var builder = new UriBuilder();
    builder.Scheme = "http://";
    builder.Host = "api.openweathermap.org";
    builder.Path = Path.Combine("data/2.5", relativePath);
    builder.Query = string.Join("&", parameters.AllKeys.Select((name) => string.Format("{0}={1}", HttpUtility.UrlEncode(name), HttpUtility.UrlEncode(parameters[name]))));
    return builder.Uri;
}

The actual query is done by following method:

private RequestStatus Execute(Uri queryURI, out string queryResponse)
    {
        queryResponse = null;
        var status = RequestStatus.OK;
        try
        {
            queryResponse = _client.DownloadString (queryURI);
            //this methods parses the code parameter of the query response//
            status = CheckResponseCode(queryResponse);
        }
        catch(WebException) {
            status = RequestStatus.Failed;
        }
        return status;
    }

Here is the deserialization of the received data:

 private CurrentWeather DeserializeCurrentWeather(string queryResponse)
    {
        var currentWeather = JsonConvert.DeserializeObject<CurrentWeather>(queryResponse);
        currentWeather.Units = this.Units;
        currentWeather.Country = CountryCodeHelper.ConvertToName((string)JObject.Parse(queryResponse).SelectToken("sys.country"));
        return currentWeather;
    }

This is called by the consumer:

public RequestStatus GetWeatherByZip(int zip, string countryCode, out CurrentWeather result)
    {
        return GetWeather(new NameValueCollection() { { "zip", CombineQueryCountryCode(zip.ToString(), countryCode) } }, out result);
    }
public RequestStatus GetWeatherByCity(string city, string countryCode, out CurrentWeather result)
    {
        return GetWeather(new NameValueCollection() { { "q", CombineQueryCountryCode(city,countryCode) } }, out result);
    }
//...//
private RequestStatus GetWeather(NameValueCollection parameters, out CurrentWeather result)
    {
        string queryResponse;
        RequestStatus status = RequestStatus.OK;
        status = Execute(BuildQueryURL(Interval.Current, parameters), out queryResponse);
        result = DeserializeCurrentWeather(queryResponse);
        return status;
    }

I excluded the async methods and forecast methods. The complete source can be found at the GitHub page.


texts: (from codeabbey) This code is supposed to add or multiply a bunch of numbers and at the end divide by a certain number and outpout the decimals

texts:
For example if the numbers are:
5 + 3 * 7 + 10 * 2 * 3 + 1 % 11
then it would multiply and add all the numbers giving 397 and divide by 11 giving 36.09 so therefore it must output 1.
My code works in this scenario but if I do more larger numbers it doesn't seem to work. This is what I have
#include <iostream>
using std::cout;
using std::cin;

int main() {

    int num1, num2;
    char opp = 'a';

    cout << "Firt nubmer";
    cin >> num1;

    while (opp != '%') {
        cin >> opp;
        cin >> num2;

        if (opp == '+') {
            num1 += num2;

        }
        else if (opp == '*') {
            num1 *= num2;

        }
        else {
            cout << num1 << " " << num2 <<  std::endl;
            num1 %= num2;

        }

    }

    cout << num1;

}


texts:
This is the first program I have written in Rust and I would like to know what some Rust experts think of it. I must be doing some stuff wrong, such as breaking code style, etc. The code differentiates simple expressions.

Two points of interest: there are verbose Box structures everywhere, and it makes the code less readable. Is there an alternative for this?

Second, I have a let ee = e.clone(); just so that I can print the value of e after calling diff. Coming from C++, Haskell, etc, this is quite strange. I understand that ownership is lost when the function is called, but I am hoping for a nicer way to do the print. One option I see is to let diff return the input as well, but this is strange.

use self::Expression::{Prod, Sum, Pow, Var, Cons};

#[derive(Debug, PartialEq, Clone)]
enum Expression {
    Cons(i32),
    Var(char),
    Prod(Box<Expression>, Box<Expression>),
    Sum(Box<Expression>, Box<Expression>),
    Pow(Box<Expression>, i32)
}

fn diff(e : Box<Expression>) -> Box<Expression> {
    match *e {
        Prod(ref a, ref b) => Box::new(Sum(Box::new(Prod(diff(a.clone()), b.clone())),
            Box::new(Prod(a.clone(), diff(b.clone()))))),
        Sum(ref a, ref b) => Box::new(Sum(diff(a.clone()), diff(b.clone()))),
        // only valid for Var^n
        Pow(ref a, ref b) => Box::new(Prod(Box::new(Cons(*b)), Box::new(Pow(a.clone(), *b - 1)))),
        Var(_) => Box::new(Cons(1)),
        Cons(_) => Box::new(Cons(0)),
    }
}

fn main() {
    let e = Box::new(Prod(Box::new(Cons(5)), Box::new(Pow(Box::new(Var('x')), 2)))); // 5*x^2
    let ee = e.clone(); // this is ugly..
    let d = diff(e); // d/dx 5*x^2 = 0*x^2 + 5*2*x^1

    println!("Differentiating {:?} yields {:?}", ee, d);
}


texts:
It's very popular to see code like this:

bool DoSomething([some arguments]);

You can't understand the result of this method by looking at its name (it could actually be a void).

What's the best approach to refactor such kind of methods?  What I have in mind is something like this:

void DoSomething([some argumens],out bool everythingIsOk);

What do you think?

EDIT

It seems that so many people prefer

bool TryDoSomething();

rather than

void DoSomething(out bool success);

But what if a method is going to have a result instead of being void?  Can we use int.TryParse pattern or we should return the result and throw an exception if something goes wrong?


texts: Using a radix tree to find case-insensitive matches in large files

texts:
I'm using a radix tree library to find case-insensitive matches from several relatively large files (~24 files each on the order ~150MB).

My current algorithm requires me to read the chars of an entire file zipped with their index because finding the offset of match in the file is a requirement.

Currently the processing is quite slow because I am doing redundant work on each new character. However, the alternative is to create subtries, which is memory intensive.

My (not well-commented) code is below... If anything is unclear, I'm happy to comment it more thoroughly.

import com.rklaehn.radixtree.RadixTree

import scala.io.Source

import java.io.File

object RadixTreeReader {
  def fromFile(filename: String): RadixTree[String, Boolean] =
    RadixTreeReader.fromLines(Source.fromFile(filename).getLines().toSeq)

  def fromLines(lines: Seq[String]): RadixTree[String, Boolean] = {
    // we mark a target as a terminal by making the associated value true
    // all substrings will not have a true value, so only exact matches
    // are true
    val pairs = lines.map(line => (line.toLowerCase, true))
    RadixTree[String, Boolean](pairs: _*)
  }
}

final case class Match(filename: String, offset: Int, target: String) {
  def hexOffset: String = offset.toHexString
}

class FileProcessor(private val filename: String, private val trie: RadixTree[String, Boolean]) {

  private val charAndIndex: Iterator[(Char, Int)] = Source.fromFile(filename).zipWithIndex

  private def isTarget(t: RadixTree[String, Boolean], prefix: String): Boolean =
    t.getOrDefault(prefix.toLowerCase, false)

  private def isEmptyWithPrefix(t: RadixTree[String, Boolean], prefix: String): Boolean = {
    val subtrieKeys = trie.subtreeWithPrefix(prefix).keys
    subtrieKeys.isEmpty || (subtrieKeys.size == 1 && subtrieKeys.head.isEmpty)
  }

  // this is the bottleneck -- all chars in sb were in the trie, but
  // we are rechecking them each time.
  // alternative is to pass a a trie into this, costing memory
  private def processCurrent(matches: Seq[Match], sb: StringBuffer, c: Char, i: Int): (Seq[Match], StringBuffer) = {
    sb.append(c)
    val s = sb.toString.toLowerCase
    (isTarget(trie, s), isEmptyWithPrefix(trie, s)) match {
      case (true, true) => (matches :+ Match(filename, i - s.length, s), new StringBuffer)
      case (true, false) => (matches :+ Match(filename, i - s.length, s), sb)
      case (false, true) => (matches, new StringBuffer)
      case _ => (matches, sb)
    }
  }

  def findMatches: Seq[Match] = {
    charAndIndex.foldLeft(Seq.empty[Match], new StringBuffer) { case ((acc, sb), (char, idx)) =>
      processCurrent(acc, sb, char, idx)
    }._1
  }
}

class DirectoryProcessor(dir: String, targetFile: String) {

  private class DirectoryReader(dir: String) {
    val files: Seq[File] = new File(dir) match {
      case d if d.exists && d.isDirectory => d.listFiles.filter(_.isFile)
      case _ => Nil
    }
  }

  private val files = new DirectoryReader(dir).files

  private val trie: RadixTree[String, Boolean] = RadixTreeReader.fromFile(targetFile)

  // Processing a file is read-only, so we can do this in parallel
  def processDirectory: collection.parallel.ParSeq[Match] = files.par.map(f => new FileProcessor(f.getPath, trie))
    .flatMap(_.findMatches)
}

Clearly I could remove unnecessary work by passing a trie (or subtrie) to FileProcessor#processCurrent where I'll traverse based on the current character, but I believe this would make the memory usage rather intractable for large enough tries.

Are there any easy optimizations that I've missed?


texts:
Thee million men write down their name and the person to their left and the person on the far left throws out his paper.  Reconstruct the list.

A List takes a while. Don't try 3 million unless you have some time.

Up front we do NOT know the remaining man on left is 0.  That is what we are looking for. The remaining here is 0 as the was test data easy to create.

public static void TAOCPthreeMillionMenTest()
{
    int numberOfMen = 30000;  // test at less than 3 million or get killed
    List<PairInt> pairs = new List<PairInt>(numberOfMen);
    for (int i = 0; i < numberOfMen; i++)
    {
        pairs.Add(new PairInt(i, i + 1));
    }
    // shuffle left
    Random rand = new Random();
    int temp;
    int j;
    //shuffl up
    for (int i = numberOfMen - 1; i > 0; i--)
    {
        j = rand.Next(i + 1);
        if (i != j)
        {
            temp = pairs[i].Rght;
            pairs[i].Rght = pairs[j].Rght;
            pairs[j].Rght = temp;
            temp = pairs[i].Left;
            pairs[i].Left = pairs[j].Left;
            pairs[j].Left = temp;
        }
    }
    foreach (PairInt pair in pairs)
    {
        //Debug.WriteLine(pair.Left + " " + pair.Rght);
        if (pair.Left == pair.Rght)
            Debug.WriteLine("pair.Left == pair.Rght");
    }
    Debug.WriteLine("");
    Debug.WriteLine(TAOCPthreeMillionManLeft(pairs));
    Debug.WriteLine("");
}
public static int TAOCPthreeMillionManLeft(List<PairInt> pairs)
{
    List<PairInt> lineEmUp = new List<PairInt>();
    int lineEmUpCountMax = 0;
    int lineEmUpCountMaxCount = 0;
    PairInt matchRght;
    PairInt matchLeft;
    int count = 0;
    foreach (PairInt pair in pairs)
    {
        count++;
        //Debug.WriteLine("new   " + pair.Left + " " + pair.Rght);
        //foreach (PairInt exist in lineEmUp)
        //{
        //    Debug.WriteLine("exist " + exist.Left + " " + exist.Rght);
        //}
        //Debug.WriteLine("");
        matchRght = lineEmUp.FirstOrDefault(x => x.Rght == pair.Left);
        matchLeft = lineEmUp.FirstOrDefault(x => x.Left == pair.Rght);
        if (matchRght != null)
        {
            if (matchLeft != null)
            {
                matchRght.Rght = matchLeft.Rght;
                lineEmUp.Remove(matchLeft);
            }
            else
            {
                matchRght.Rght = pair.Rght;
            }
        }
        else if (matchLeft != null)
        {
            matchLeft.Left = pair.Left;
        }
        else
        {
            lineEmUp.Add(pair);
            if (lineEmUpCountMax < lineEmUp.Count)
            {
                lineEmUpCountMax = lineEmUp.Count;
                lineEmUpCountMaxCount = count;
            }
            //Debug.WriteLine("lineEmUp.Count " + lineEmUp.Count);
        }
    }
    // lineEmUp should have only one entry
    if (lineEmUp.Count != 1)
    {
        Debug.WriteLine("");
        Debug.WriteLine("lineEmUp.Count != 1");
        foreach (PairInt pair in lineEmUp)
        {
            Debug.WriteLine(pair.Left + " " + pair.Rght);
        }
        Debug.WriteLine("");
    }
    return lineEmUp[0].Left;
}

public class PairInt
{
    public int Left { get; set; }
    public int Rght { get; set; }
    public PairInt(int left, int rght)
    {
        Left = left;
        Rght = rght;
    }
}

I tried a double dictionary but could not make it work.


texts:
Please give feedback on what I could do better next time. This is an Angular 1.x landing page I made for a pretend car dealership.

Here is what it looks like.

Here is the app.js:

(function(){

'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp',[]);

})();

Here is my car-slide.js directive that holds some car data, and has a controller for changing the current car picture and tagline:

angular.module('myApp').directive('carSlide', CarSlide);

function CarSlide(){
return {
   restrict: 'E',
   templateUrl: 'partials/car-slide.html',
   controller:function($interval){

    this.currentCar = 0;
    var self = this;

    function changeCar(){
      if (self.currentCar == 0){
        self.currentCar = 1;
      } else {
        self.currentCar = 0;
      }
    }

    $interval(changeCar, 4000);

    this.carData = [{
                    class:'A4',
                    name: "Audi A4",
                    tagline: "The time is now.",
                    img: "img/big/car1.jpg"
                    },
                    {
                    class:'A5',
                    name: "Audi A5",
                    tagline: "Do you like power?",
                    img: "img/big/car2.jpg"}
                  ];

  },
  controllerAs:'carCtrl'
};

};

Here is the directive for the slider on the bottom. All it does is change the header from one car type to another:

angular.module('myApp').directive('carTypeSlide', CarTypeSlide);

function CarTypeSlide() {
    return {
        restrict: 'E',
        templateUrl: 'partials/car-type-slide.html',

        controller: function($interval) {
            var self = this;
            this.carTypes = [
                "Sedans",
                "Crossovers and Minivans",
                "Hybrids",
                "Compacts"
            ];
            var initial = 0;
            var currType = 0;
            this.showType = this.carTypes[initial];

            $interval(changeType, 3000);

            function changeType() {

                currType++;

                self.showType = self.carTypes[currType];

                if (currType === self.carTypes.length) {
                    currType = 0;
                    self.showType = self.carTypes[currType];
                }

            }

        },
        controllerAs: 'carTypeCtrl'
    };
};

Here is the repo for it.

I have put AngularJS on pause and am trying to learn ES2015 right now, and then building a simple app with that. Do you think learning ES2015 will help with frameworks like Angular/React?


texts: Encapsulating Logic to Reuse in Various Contexts

texts:
I'm experimenting with ways to reuse code throughout a Rails web app. I'm interested in feedback concerning one such approach!

Context

A user's request may be scoped to a physical location so that the view shows location-relevant information. In most cases, the location is stored in a cookie. It's possible for location to be overridden via query parameters (?where= or ?location=). When location is not in a cookie or in the query string, depending on where the code executes, I'll want to provide some other location.

Here's what I came up with:

class LocationResolver
  def initialize(locations)
    @locations = locations
  end

  def call(strategy)
    [*strategy].map { |strat| strat.(@locations) }.find(&:itself)
  end

  class QueryStrategy
    def initialize(params)
      @params = params
    end

    def call(locations)
      locations.find { |x| x.slug == slug }
    end

    private

    def slug
      @slug ||= @params.values_at(:where, :location).find(&:itself)
    end
  end

  class CookieStrategy
    def initialize(cookies)
      @cookies = cookies
    end

    def call(locations)
      content.presence && locations.find { |x| x.id == content["id"] }
    end

    private

    def content
      @content ||= JSON.parse(@cookies.fetch(:location, "{}"))
    end
  end

Given a simple Location implementation:

Location = Struct.new(:id, :slug) do
  def self.all
    [
      new(1, "one"),
      new(2, "two")
    ]
  end

  def self.anywhere
    new(nil, "anywhere")
  end
end

Usage inside a controller might look like this:

class PropertiesController << ApplicationController
  def effective_location
    @effective_location ||=
      LocationResolver.new(Location.all).([
        LocationResolver::QueryStrategy.new(request.query_parameters),
        LocationResolver::CookieStrategy.new(request.cookies),
        -> (_) { Location.anywhere }
      ])
  end
end

Dislikes

Feels complex

Likes

A strategy can be reused.
Strategies can be reordered or included/excluded depending on your needs.
Strategies can receive only context they require to do their job.
Strategies can be created without modifying the resolver
Use of .call allows defining a strategy at runtime.
Easy to stub and test.

What do you think?

What do you think conceptually?
What other approaches do you prefer?
What in particular do you like or dislike about this approach?
Any glaring issues?
Are Resolver and Strategy suitable names?

Thank you so much! :)


texts:
I started learn OOP in Python. I have OOP basics in Java and apparently I have a problem with thinking in OOP in Python (and using the best functionalities and syntax). I have doubts about my OOP design in web scraping for a local book review page. So the basic idea is scraping information about book with the user reviews for that books.

The structure of the Python package:

/bookscraper
    __init__.py
    book.py
    comment.py
    parsers.py

parsers.py:

from urllib.request import urlopen
from bs4 import BeautifulSoup
from bookscraper.book import Book
from bookscraper.comment import Comment

class Parser:
    def __init__(self, url, name, search_url):
        self.url = url
        self.name = name
        self.search_url = search_url

class DatabazeKnih(Parser):
    PAGE_URL = 'http://www.databazeknih.cz/'
    NAME = 'Databáze knih'
    SEARCH_URL = 'search?q={}&hledat=&stranka=search'

    def __init__(self):
        super().__init__(DatabazeKnih.PAGE_URL, DatabazeKnih.NAME, DatabazeKnih.SEARCH_URL)

    def search(self, name):
        self.search_html = urlopen(DatabazeKnih.PAGE_URL + DatabazeKnih.SEARCH_URL.format(name))
        self.book_link = DatabazeKnih.PAGE_URL + self.get_book_link() + '?show=alldesc'
        return self.get_book_info()

    def get_book_page(self):
        return urlopen(self.book_link)

    def get_book_link(self):
        soup = BeautifulSoup(self.search_html, 'html.parser')
        return soup.find(type='book').attrs['href']

    @staticmethod
    def parse_comment(comment):
        user = comment.find('a').string
        text = comment.find('p', {'class': 'odtopm new2 justify'}).text
        date = comment.find('span', {'class': 'pozn_lightest odleft_pet'}).string
        return user, text, date

    @staticmethod
    def get_comments(soup):
        comments_objects = []
        comments = soup.find_all('div', {'class': 'komholdu'})
        for comment in comments:
            user, text, date = DatabazeKnih.parse_comment(comment)
            comments_objects.append(Comment(user, text, date))
        return comments_objects

    @staticmethod
    def get_authors(soup):
        return [author.string for author in soup.find(itemprop='author').find_all('a')]

    def get_book_info(self):
        soup = BeautifulSoup(self.get_book_page(), 'html.parser')
        title = soup.find(itemprop='name').string
        rating = soup.findAll('a', {'class': 'bpoints'})[0].string
        text = soup.find(itemprop='description').string
        authors = DatabazeKnih.get_authors(soup)
        year = soup.find(itemprop='datePublished').string
        comments = DatabazeKnih.get_comments(soup)
        return Book(title, rating, text, authors, year, comments)

Then there are the Book and Comment classes. I will add some functionality to these classes. Now I prepared only constructors:

class Book:
    def __init__(self, title, rating, text, authors, year, comments):
        self.title = title
        self.rating = rating
        self.text = text
        self.authors = authors      # this is a list
        self.year = year
        self.comments = comments    # this is a list

class Comment:
    def __init__(self, user, text, date):
        self.user = user
        self.text = text
        self.date = date

Then I can't get info about book via creating parser object:

from bookscraper.parsers import DatabazeKnih

parser = DatabazeKnih()
book = parser.search('ydris')  # Name of the book

My code is working, but is it a good OOP design? I have some doubts about the design of methods in the DatabazeKnih class. In search method I set two attributes I found it is not a good practice, but how should I rewrite? Should I create setters for this two attributes?


texts:
I started to teach myself Haskell recently. Here is some code I wrote to convert a roman numeral into an arabic numeral:

import Control.Arrow ((>>>))
import Data.Maybe (fromJust)

fromRoman :: String -> Int
fromRoman = translateFromRoman >>> applyNegationRule >>> sum

translateFromRoman :: String -> [Int]
translateFromRoman = map (\r -> fromJust $ lookup r [('I',1),('V',5),('X',10),('L',50),('C',100),('D',500),('M',1000)])

applyNegationRule :: [Int] -> [Int]
applyNegationRule [x]      = [x]
applyNegationRule (x:y:xs) = (if x < y then -x else x) : applyNegationRule (y:xs)

I like it quite a bit. But some questions remain. First of all I never (at least I can't remember) came across (>>>) in other code so far. Everyone seems to use:

fromRoman :: String -> Int
fromRoman = sum . applyNegationRule . translateFromRoman

It produces the same output, but for me as someone used to read from top left to bottom right the first variant is just more readable. You could also write it like this:

fromRoman :: String -> Int
fromRoman = translateFromRoman
        >>> applyNegationRule
        >>> sum

To make it even more text like readable. So where's the catch?

Another question arising from this code is: Should I define the functions translateFromRoman and applyNegationRule in fromRoman ... where? Again I see it quite a lot but IMHO it also lacks readability. At the moment readability is one of the most important metrics for me to determine code quality.

And last but note least: Am I doing something bad in translateFromRoman and applyNegationRule or are there some better (faster/shorter or ofcourse more readable) alternatives?


texts:
Description:
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

coins = [1, 2, 5], amount = 11, return 3 (11 = 5 + 5 + 1)
coins = [2], amount = 3, return -1.

Code:
class Solution {
    public int coinChange(int[] coins, int amount) {
        if (amount == 0) return 0;
        if (amount <  0) return -1;

        int min = -1;
        for (int coin : coins) {
            int currentMin = coinChange(coins, amount - coin);

            // if amount is less than coin value
            if (currentMin >= 0) {
                min = min < 0 ? currentMin : Math.min(currentMin, min);
            }
        }

        return min < 0 ? -1 : min + 1;
    }
}

Questions:
This question has slight deviation from normal one where we just need to return 0, returning -1 got me confused and I found it really hard to think in terms of recursion and handling edge cases.
PS: The solution works perfectly.


texts:
My page contains: GridView1, GridView2, Button1, Button2, DropDownList1 I bind Gridviews to the table selected in dropdown like this:

Dim results as DataTable
Select Case ddl1.SelectedValue
    Case 0
        Dim cl as ClassZero = new ClassZero()
        results = cl.GetClassZeroNames()
    Case 1
           Dim cl as ClassOne = new ClassOne()
        results = cl.GetClassOneNames()
    Case 2
         Dim cl as ClassTwo = new ClassTwo()
        results = cl.GetClassTwoNames()
End Select
GridView1.DataSource = results
GridView1.DataBind()

Then I have two buttons with the following code:

Protected Sub btn1_Click(sender As Object, e As EventArgs) Handles btn2.Click
    Select Case ddl1.SelectedValue
        Case 0
             Dim cl as ClassZero = new ClassZero()
        results = cl.RunInsert()
        Case 1
             Dim cl as ClassOne = new ClassOne()
        results = cl.RunInsert()
        Case 2
             Dim cl as ClassTwo = new ClassTwo()
        results = cl.RunInsert()
    End Select
End Sub

And

Protected Sub btn2_Click(sender As Object, e As EventArgs) Handles btn2.Click
    Select Case ddl1.SelectedValue
        Case 0
             Dim cl as ClassZero = new ClassZero()
        results = cl.RemoveFromZero()
        Case 1
            Dim cl as ClassOne = new ClassOne()
        results = cl.RemoveFromOne()
        Case 2
            Dim cl as ClassTwo = new ClassTwo()
        results = cl.RemoveFromTwo()
    End Select
End Sub

For me it looks like a lot of overhead. How can I improve then design and only specify that I'm working on the following record in dropdown list without specifying the Case condition every time? Should I change my design or leave it like it is?

RunZero, RunOne, RunTwo, RemoveZero, RemoveOne, RemoveTwo, RemoveThree - Execute six different stored procedures.


texts: Stochastic gradient descent squared loss

texts:
I have implemented stochastic gradient descent in matlab and I would like to compare my results with another source but the error I am getting is higher (I am using squared error). I am worried I am misunderstanding the algorithm or have a bug. I have done trial and error parameter tuning, and am quite confident I have appropriate value for B, and know that I am working with the same data as my comparison. Please let me know what can be improved and if there is a mistake.

    % [w] = learn_linear(X,Y,B)
    %
    % Implement the online gradient descent algorithm with a linear predictor
    % and minimizes over squared loss.
    % Inputs:
    %     X,Y - The training set, where example(i) = X(i,:) with label Y(i)
    %     B - Radius of hypothesis class.
    % Output:
    %     w - predictor (as a row vector) from the hypothesis class (norm(w) <= %B)

    function [w] = learn_linear_sq_error(X, Y, B)
        [r c] = size(X);
        w = zeros(1, c);
        sum_w = zeros(1, c);
        % number of iterations
        T = 1000;

        % Run T iterations of online gradient descent:
        for t = 1:T,
            % Calculate step size for the current iteration.
            eta_t = 1 / sqrt(t);

            % Choose a random sample, and calculate its gradient.
            i_t = round(rand(1) * (r - 1)) + 1;
            g_t = calc_g_t(X(i_t, :), Y(i_t), w);

            % Apply the update rule/projection using the chosen sample, by %finding
            % the w that minimizes '|w - (w_t - eta_t * g_t)|' while          %maintaining norm(w) <= B.
            pw = w - eta_t * g_t;
            norm_pw = norm(pw);
            if norm_pw <= B
                w = pw;
            else
                w = B * pw / norm_pw;
            end

        % accumulate the sum in preparation for calculating the final average.
            sum_w = sum_w + w;

        end

        % Return the average of all intermediate w's.
        w = sum_w / T;
    end

    %
    % Calculate the sub gradient, with respect to squared loss, for a given sample
    % and intermediate predictor.
    % Inputs:
    %     x,y - A sample x (given as a row vector) and a tag y in R.
    %     w - our current predictor.
    % Output:
    %     g_t - the gradient (as a row vector) for the given values of x, y, w.

    function g_t = calc_g_t(x, y, w)

        g_t = 2 * (w*x' - y) * x;

    end


texts: Script that fixes YML SIDs to be simplified for production

texts:
I work with YML files that include SIDs and the following structure:

    title:
  "2": "content a" # key: comment
  "3": "content b" # key: comment
  "4": "content c" # key: comment
  "5": "content d" # key: comment
  "6": "content e" # key: comment

Usually, I have to remove some strings (note I never remove the number 1 or 2) so my new file looks like this:

    title:
  "2": "content a" # key: comment
  "3": "content b" # key: comment
  "5": "content d" # key: comment
  "6": "content e" # key: comment

I need to rearrange the SIDs in order to have a sequence without any gap (in this case 2, 3, 4, 5, 6) independently on the content. For that reason I have written the following script. It works properly but I need to bring it into production so I need your help to reduce its complexity, make it clear and simpler or any advice you may have for a beginner (in both, Python and Stack Exchange).

import re, os

file=input ('YML file name: ')

#read the file and store its content as a list
os.chdir('/home/balaclava/Desktop/Scripts/YML fixer/')
rdfile= open(file)
cont=rdfile.readlines()
rdfile.close()

#list to store the reviewed strings
newfile=[]
newfile.append(cont[0]+cont[1])

#Get the second string SID as reference
numRegex = re.compile(r'\d+')
act=numRegex.search(cont[1])
global refnum
refnum=int(act.group())

#Loop for each string (-2 due to the two first string are excluded)
for i in range(len(cont)-2):
    act=numRegex.search(str(cont[i+2]))
    temp=int(act.group())
#If the SID is correct, add item to newlist, else, fix it and add the item to the list.
    if temp == (refnum+1):
        newfile.append(cont[i+2])
    else:
        temp= (refnum+1)
        change=numRegex.sub(str(temp), cont[i+2])
        newfile.append(change)
    refnum += 1

#overwrite the file with the newlist content
with open (file,'w') as finalfile:
    finalfile.write(''.join(newfile))
    finalfile.close()


texts:
When working on a large codebase, I often need to switch between deeply nested directories quickly. To make my life easier, I came up with a bookmarking script.

#!/bin/bash

bm_list() {
    for i in "${!BOOKMARKS[@]}"; do
        echo -e $i'\t'"${BOOKMARKS[$i]}" ;
    done
}

bm_go() {
    cd "${BOOKMARKS[$1]}"
}

bm_add() {
    for i in "${!BOOKMARKS[@]}"; do
        [[ "$1" == ${BOOKMARKS[$i]} ]] && return
    done
    BOOKMARKS+=("$1")
}

bm_clear() {
    unset BOOKMARKS
}

bm_delete() {
    unset BOOKMARKS[$1]
}

bm_compact()
{
    local SIFS="$IFS"; IFS=
    BOOKMARKS=("${BOOKMARKS[@]}")
    IFS="$SIFS"
}

bm_load() {
    local bmfile=${1:-~/.bookmarks}
    local SIFS="$IFS"; IFS=$'\n'
    bm_clear
    while read -d ''; do BOOKMARKS+=("$REPLY"); done < "$bmfile"
    IFS="$SIFS"
}

bm_save() {
    local bmfile=${1:-~/.bookmarks}
    printf '%s\0' "${BOOKMARKS[@]}" > "$bmfile"
}

bm_help() {
    cat <<-EOF
bm: bookmark directories
Usage:
    bm                   bookmark current directory
    bm -l
    bm list              list bookmarks
    bm index
    bm -g index
    bm go index          cd to bookmark at index
    bm -d index
    bm delete index      delete bookmark at index
    bm -s [filename]
    bm save [filename]   save bookmarks in the file (default ~/.bookmarks)
    bm -L [filename]
    bm load [filename]   load bookmarks from the file (default !/.bookmarks)
    bm -c
    bm clear             remove all bookmarks
    bm -C
    bm compact           compact indices to a sequential list
EOF
}

bm() {
    local command=$1; shift
    case $command in
        -l | list ) bm_list ;;
        -g | go ) bm_go "$1" ;;
        -d | delete ) bm_delete "$1";;
        -s | save ) bm_save "$1" ;;
        -c | clear ) bm_clear ;;
        -C | compact ) bm_compact ;;
        -L | load ) bm_load "$1" ;;
        '') bm_add "$PWD" ;;
        *) [[ "$command" =~ [0-9]+ ]] && bm_go "$command" || bm_help ;;
    esac
}


texts:
I want to play some audio of two byte arrays. I was wondering whether it would be better to play them as two separate arrays both calling the method, or to put them into one array and play it from there.

Note: The starting from position 4 because the first 4 bytes are saved for the sequence number in the array.

All in one array:

   byte[] das = ByteBuffer.allocate((temp.length-4)*2)
                        .put(Arrays.copyOfRange(temp, 4, temp.length - 4))
                        .put(Arrays.copyOfRange(udpPacketBytes, 4, udpPacketBytes.length - 4))
                        .array();
                player.playBlock(das);

or split like this:

  byte[] filteredByteArray = Arrays.copyOfRange(temp, 4, temp.length - 4);

                player.playBlock(filteredByteArray);

                // play the current one
                byte[] fba = Arrays.copyOfRange(udpPacketBytes, 4, udpPacketBytes.length - 4);

                player.playBlock(fba);

I was also wondering whether there'd be a way to calculate the complexity of the two.


texts: Counting how many times each distinct word appears in an input

texts:
In chapter 3 of Koenig's Accelerated C++, he asks the reader to write a program that performs the task described in the title. At this point, he has only introduced the built-in types, io-types, and vectors, so maps are not allowed. I have written a program that does this, but it is lengthy and requires a number of objects that essentially duplicate existing vectors.

Note: the use of while (cin >> input) will not terminate without an explicit end of line character because of the input type, so a better way to handle the input would be nice to have!

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using std::cin;
using std::cout;
using std::vector;
using std::string;
using std::endl;

int main ( int argc, char** argv )
{
    string input;
    vector<string> input_arr;

    cout << "Please enter a sentence or list of words, separated by spaces,"
            "and terminated by an EOL character(^d): ";

    while(cin >> input) {
        input_arr.push_back(input);
    }

    sort(input_arr.begin(), input_arr.end());

    vector<string>::size_type len = input_arr.size();

    uint count = 0;
    vector<uint> count_arr;
    string current_string = input_arr[0];
    vector<string> unique_words;
    unique_words.push_back(input_arr[0]);

    for (vector<string>::size_type i = 0; i < len; i++) {

        count_arr.push_back(0);

        if (current_string != input_arr[i]) {
            count +=1;
            current_string = input_arr[i];
            count_arr.push_back(0);
            unique_words.push_back(input_arr[i]);
        }

        count_arr[count] += 1;
    }

    cout << endl;

    for (int j = 0; j <= count; j++) {
        cout << endl << "The word " << unique_words[j] << " occured " << count_arr[j] << " times!";
    }

    cout << endl;

    return 0;
}

In Python, I could achieve this in about 5 lines, for example:

from collections import defaultdict

print("Please enter some text: ")

input_arr = input().split()
d = defaultdict(int)

for k in input_arr:
    d[k] += 1

for key in d.keys():
    print("The word %s occurs %d times!\n" %(key, d[key]))

I am looking for a better way to accomplish this in C++, preferably not using std::maps, since the author probably put this exercise at this stage in the book for a reason. I'm also just learning C++, do I'd appreciate any advice on best practices that I'm violating in this example.


texts: User defined XIRR function: exception handling

texts:
This is my first attempt at Python. I started with some code from https://github.com/peliot/XIRR-and-XNPV (which aims to mimic the Excel function XIRR) and tried to 'improve' on it (and the Excel version). But I would like to know if in these few lines I already made beginner's mistakes. I'm particularly interested to learn whether there is a more elegant way to handle the exceptions (an 'improvement' of mine), because this looks a bit clunky. (This is not the only change compare to the original, so the other bits may be not completely correct either.)

Note that the function newton itself may also give rise to an immediate exception.

import datetime
from scipy import optimize

def xnpv(rate, cashflows):
    t0 = min(cashflows, key = lambda t: t[0])[0]
    return sum([cf/(1+rate)**((t-t0).days/365.0) for (t,cf) in cashflows])

def xirr(cashflows,guess=0.1):
    try:
        outc = optimize.newton(lambda r: xnpv(r, cashflows), guess,
                               maxiter=100)
        if outc.imag == 0:
            return outc
        else:
            raise
    except (RuntimeError, OverflowError):
        try:
            outc = optimize.newton(lambda r: xnpv(r, cashflows), -guess,
                                   maxiter=100)
            if outc.imag == 0:
                return outc
            else:
                raise
        except (RuntimeError, OverflowError):
            return float("NaN")

#cftest = [(datetime.date(2001, 12, 5), -2000), (datetime.date(2007, 12, 5), -10), (datetime.date(2017, 12, 5), 20)]
cftest = [(datetime.date(2001, 12, 5), -2000), (datetime.date(2000, 12, 5), -1000), (datetime.date(2017, 12, 5), 2000)]
#cftest = [(datetime.date(2001, 12, 5), -2000), (datetime.date(2007, 12, 5), -1000), (datetime.date(2017, 12, 5), 20)]
print(cftest)
print(xirr(cftest))


texts:
The minimum window substring problem from leetcode.com asks:

  Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity \$O(n)\$.

  For example,

  S = "ADOBECODEBANC"
  T = "ABC"

  Minimum window is "BANC".

I post two versions of code. The differences between two versions of code is, the first one will move the start index when there is a match, the 2nd version will not move the start index when there is a move.

Wondering if logics are both correct? If both have the correct logic, which one do you think has better performance? I have did basic testing and post my test cases below. Using Python 2.7.

from collections import defaultdict
import sys

def minWindow(source, pattern):
    targetCount = defaultdict(int)
    currentCount = defaultdict(int)
    for ch in pattern:
        targetCount[ch] += 1
    start = 0
    validCount = 0
    minSize = sys.maxint
    for index in range(len(source)):
        if source[index] not in targetCount:
            continue
        if currentCount[source[index]] < targetCount[source[index]]:
            validCount += 1
        currentCount[source[index]] += 1
        while validCount == len(targetCount):
            if source[start] not in targetCount:
                start += 1
            elif currentCount[source[start]] > targetCount[source[start]]:
                currentCount[source[start]] -= 1
                start += 1
            else:
                minSize = min(minSize, index-start+1)
                currentCount[source[start]] -= 1
                validCount -= 1
                start += 1
    return (minSize, start-1)

def minWindowv2(source, pattern):
    targetCount = defaultdict(int)
    currentCount = defaultdict(int)
    for ch in pattern:
        targetCount[ch] += 1
    start = 0
    validCount = 0
    minSize = sys.maxint
    for index in range(len(source)):
        if source[index] not in targetCount:
            continue
        if currentCount[source[index]] < targetCount[source[index]]:
            validCount += 1
        currentCount[source[index]] += 1
        while validCount == len(targetCount):
            if source[start] not in targetCount:
                start += 1
            elif currentCount[source[start]] > targetCount[source[start]]:
                currentCount[source[start]] -= 1
                start += 1
            else:
                minSize = min(minSize, index-start+1)
                break
    return (minSize, start)

if __name__ == "__main__":
    print minWindow("ADOBECODEBANC","ABC")
    print minWindowv2("ADOBECODEBANC", "ABC")


texts: Remaking std::to_string in C++ with UDLs (User Defined Literals)

texts:
I would like some feedback on what I should change with my semi remake of std::to_string with UDLs (user-defined literals).

This is compiled and working on linux with C++11 using g++.

#include <deque> // if you use vectors instead you have to add them to the
//string in reverse order (no push_front())
#include <string>

std::string operator"" _str(unsigned long long int num)
{
  std::deque<char> digits;
  for(char i = 0; num != 0;num = num / 10)
  {
      i = '0'+(num % 10);
      digits.push_front(i);
  }
  std::string converternum;
  for(auto i = 0; i< digits.size();i++)
    converternum += digits[i];
  return converternum;
}

char * operator"" _cstr(unsigned long long int num)
{
   std::deque<char> digits;
   for(char i = 0; num != 0;num = num / 10)
   {
     i = '0'+(num % 10);
     digits.push_front(i);
   }
   std::string converternum;
   for(auto i = 0; i< digits.size();i++)
   converternum += digits[i];
   char * string = (char *)converternum.c_str();
   return string;//converternum.c_str();
}


texts:
This is a fairly short code snippet, but it made me a little headache, because it is hard to understand, isn't it?

// You have to be in both 'group' and 'board' to get access (or be a superuser)
if ( ( !$is_in_group || !$is_in_board ) && !$is_superuser) {
    die('No access');
}

This code is from a download page, where registered users can download files. Only users within a certain board and group are allowed to download files. The three variables are just for this demo. The values are coming from a CMS function.

Do you have a more readable or better way to verifying access here?


texts:
This is a token generating library for Go that runs on top of Redis. I'm using it as part of a larger projects. The library needs to be able to generate and validate tokens and return the associated user IDs.

If you see any bugs or obvious glaring issues, please let me know.

// auth project auth.go
package token

import (
    "crypto/rand"
    "errors"
    "fmt"
    "gopkg.in/redis.v3"
    "time"
)

type Token struct {
    str    string
    expire time.Time
    id     int64
}

func NewToken(l time.Duration, id int) (Token, error) {
    b := make([]byte, 32)
    _, err := rand.Read(b)
    if err != nil {
        return Token{}, err
    }
    t := Token{str: fmt.Sprintf("%x", b), expire: time.Now().Add(l).UTC(), id: int64(id)}
    return t, t.Validate()
}

func (t *Token) SetToken(s string) error {
    t.str = s
    return t.Validate()
}

func (t *Token) GetID() int {
    return int(t.id)
}

func (t *Token) GetExpire() time.Time {
    return t.expire
}

func (t *Token) Validate() error {
    if time.Since(t.expire) >= 0 || t.id == 0 {
        return errors.New("TOKEN_EXPIRED")
    }
    if t.id < 0 {
        return errors.New("TOKEN_INVALID_ID")
    }
    if len(t.str) != 64 {
        return errors.New("TOKEN_INVALID_LENGTH")
    }
    return nil
}

func (t *Token) Store(r *redis.Client) error {
    if t.Validate() != nil {
        return t.Validate()
    }
    flag, err := r.SetNX(t.str, t.id, -time.Since(t.expire)).Result()
    if !flag {
        return errors.New("duplicate stored token")
    }
    return err
}

func (t *Token) Load(r *redis.Client) error {
    id, err := r.Get(t.str).Int64()
    t.id = id
    if t.Validate() != nil {
        return t.Validate()
    }
    return err
}


texts: Comparing a list of messages with a list inside an object

texts:
int i = 0
for ( expectedErrors in errors ) {
    final List<String> actualErrors = new ArrayList<>()
    actualRequestMessages?.get(i++)?.errorData?.errors?.each {
        item -> actualErrors.add("${item.message}")
    }
    assert [ ] == ((actualErrors - expectedErrors) + (expectedErrors - actualErrors)), [expectedErrors, actualErrors, "Expected Errors doesn't match actual"]
}

Currently, I am comparing actual error messages inside actualRequestMessages.errorData.errors with a list of expectedErrors as mentioned above. Is there a better way of doing it in Groovy?

Errors come from spock test in the form of a list of errors:

errors
[[error1],[error1,error2,error3]]