texts:
https://leetcode.com/problems/sliding-window-median/

  Median is the middle value in an ordered integer list. If the size of
  the list is even, there is no middle value. So the median is the mean
  of the two middle value.

  Examples: [2,3,4] , the median is 3

  [2,3], the median is (2 + 3) / 2 = 2.5

  Given an array nums, there is a sliding window of size k which is
  moving from the very left of the array to the very right. You can only
  see the k numbers in the window. Each time the sliding window moves
  right by one position. Your job is to output the median array for each
  window in the original array.

  For example, Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

  Therefore, return the median sliding window as [1,-1,-1,3,5,6].

  Note: You may assume k is always valid, ie: k is always smaller than
  input array's size for non-empty array. Answers within 10^-5 of the
  actual value will be accepted as correct.

Please review for performance. also I am not sure about GetID function is there a smarter way to get the same result of unique number and sorting for median?

using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TreeQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/sliding-window-median/
    /// </summary>
    [TestClass]
    public class SlidingWindowMedianTest
    {
        [TestMethod]
        public void ExampleTest()
        {
            int[] nums = { 1, 3, -1, -3, 5, 3, 6, 7 };
            int k = 3;
            double[] expected = { 1, -1, -1, 3, 5, 6 };
            double[] res = SlidingWindowMedian.MedianSlidingWindow(nums, k);
            CollectionAssert.AreEqual(expected, res);
        }

        [TestMethod]
        public void ExampleTestFailed()
        {
            int[] nums = { 1, 4, 2, 3 };
            int k = 4;
            double[] expected = { 2.5 };
            double[] res = SlidingWindowMedian.MedianSlidingWindow(nums, k);
            CollectionAssert.AreEqual(expected, res);
        }

        [TestMethod]
        public void ExampleTestOverFlow()
        {
            int[] nums = { 2147483647, 2147483647 };
            int k = 2;
            double[] expected = { 2147483647.0 };
            double[] res = SlidingWindowMedian.MedianSlidingWindow(nums, k);
            CollectionAssert.AreEqual(expected, res);
        }

        [TestMethod]
        public void ExampleFailed2()
        {
            int[] nums = { 5, 2, 2, 7, 3, 7, 9, 0, 2, 3 };
            int k = 9;
            double[] expected = { 3.0, 3.0 };
            double[] res = SlidingWindowMedian.MedianSlidingWindow(nums, k);
            CollectionAssert.AreEqual(expected, res);
        }
    }

    public class SlidingWindowMedian
    {
        public static double[] MedianSlidingWindow(int[] nums, int k)
        {
            var res = new List<double>();
            var med = new SortedList<long, int>();
            for (int i = 0; i < nums.Length; i++)
            {
                med.Add(GetId(i, nums), nums[i]);
                if (med.Count > k)
                {
                    med.Remove(GetId(i - k, nums));
                }

                if (med.Count == k)
                {
                    if (k % 2 == 0)
                    {
                        res.Add( ((long)med[med.Keys[k / 2 - 1]]  + med[med.Keys[k / 2]])/2.0 );
                    }
                    else
                    {
                        res.Add(med[med.Keys[k / 2]]);
                    }
                }
            }
            return res.ToArray();

        }

        private static long GetId(int i, int[] nums)
        {
            return Convert.ToInt64(nums[i]) * nums.Length + i;
        }
    }

}


texts: Django model to do accounting for a Litecoin miner pool

texts:
I'm coming from Java so I am used to performing calculations I require in separate functions. I would like to know if the below code makes sense in my Django model especially the loop and calling functions from within functions.

The aim of this is to create a backend for multiple Litecoin miners (L3's). Every miner will contribute to the same pool but be plugged in at different times. Therefore each will get its own time stamp. Each month I will pull the total pool amount (pulled from api) and use the total amount of hours contributed to the pool to calculate the litecoins-to-hour ratio. This ratio I can then multiply to each miners' hours worked for the month to determine that particular miners Litecoin earned.

class L3(models.Model):
    user = models.ForeignKey(User, related_name="L3")
    MachineID = models.CharField(max_length=256)
    TimeOnline = models.DateTimeField()
    Commission = models.IntegerField(default='10')
    TimeOffline = models.IntegerField(default='0')

    def indivMachineHoursWorked(self):
        this_month = datetime.now().month
        if self.TimeOnline == this_month:
            x = datetime.now() - self.TimeOnline
        else:
            x = datetime.now() - datetime.today().replace(day=1) #need to update hour to 0 too i.e. start of month
        return x

    def totalMachineHoursWorked(self):
        L3_total = L3.objects.all()
        hrs=0
        for l3 in L3_total:
            hrs =+ l3.indivMachineHoursWorked()
        return hrs

    def btcToHour(self):
        main_api = 'https://api.nicehash.com/api?method=balance&id=123456&key=01234567-abcd-dcba-abcd-0123456789abc'
        url = main_api
        json_data = requests.get(url).json()
        print(json_data)
        balance1 = json_data['result']['balance_confirmed']
        print(balance1)
        btc2hour = balance1/self.totalMachineHoursWorked()
        return btc2hour

    def indivMachineTurnover(self):
        return self.indivMachineHoursWorked()*self.btcToHour()

    def __str__(self):
        return self.user.get_full_name()


texts:
I just wanted to know if this looks like a good way of reading a config file. Is this code good? Is it clean and easy to follow?

<?
    /* class to parse a txt config file
     *
     * Boolean like string values (on/off, yes/no, true/false) will return true/false
     * Numberic string values will return real numeric values
     *
     * Ingore error on input.
     *
     * useage: $cp = new config_parse();
     *         $config_parse->parse_file($input_file);
     *
     * $input_file - the file to be parsed. If a full path is not specified, will assume the file is in the same path as the script calling this class.
     * returns an array of config values in their correct type or false if an error is encountered.
     *
     */

    class config_parse {

        var $config_array;
        var $config_file;
        var $comment_marker = "#";
        var $bool_true_array = array("on", "yes", "true");
        var $bool_false_array = array("off", "no", "false");

        function config_parse() {

            $this->config_array = array();
            $this->config_file = "";

        }

        // parse the config file into the config array
        public function parse_file($input_file) {

            if ($input_file=="") {
                return false;
            }

            // locate the config file
            if (file_exists($input_file)) {
                $this->config_file = $input_file;
            } elseif (file_exists(dirname(__FILE__) . $input_file)) {
                $this->config_file = dirname(__FILE__) . $input_file;
            } else {
                return false;
            }

            $this->do_parse();
            return $this->config_array;

        }

        // read the lines of the file
        private function do_parse() {
            $handle = fopen($this->config_file, "r");
            if ($handle) {
                while (($line = fgets($handle)) !== false) {
                    $this->process_config_line($line);
                }
                fclose($handle);
            } else {
                return false;
            }
        }

        // remove blank lines and comments
        private function process_config_line($line) {
            $line = trim($line);

            // blank
            if ($line=="") {
                return;

            // comment
            } elseif (substr($line,0,1)==$this->comment_marker) {
                return;

            // actual value
            } else {
                $this->process_name_value($line);
            }
        }

        // process a line with an actual name/value pair in it.
        private function process_name_value($line) {

            $line_split = explode("=",$line);
            $name = trim($line_split[0]);
            $value = trim($line_split[1]);

            $this->config_array[$name]=$this->process_value($value);
        }

        private function process_value($value) {

            if (in_array($value,$this->bool_true_array)) return true;
            if (in_array($value,$this->bool_false_array)) return false;
            if (is_numeric($value)) return $value+0;
            return $value;

        }
    }
    ?>


texts: Populating form contents from GET - especially radio buttons

texts:
I have a form written in the usual way. After submitting, if there are errors in the form, the form page itself is the target of the redirect, with a query string appended. The query string contains the error messages, but also the values submitted with the form. The query string and its format are provided by a 3rd-party, so I cannot switch to using POST, nor make any other changes on their processing logic. I just get the string and make the best of it.

Since the URL is "different", the form's values aren't preserved. The browser treats it as a fresh form and therefore blanks it. Not good, since the user won't want to re-enter everything. So, the first step was deciding whether to use JavaScript or PHP to repopulate the form, and I went with PHP.

Consequently, the form now has entries that look a little something like this:

  How many years have you been in business?

    <input id="partner_business_years" name="partner_business_years" class="element text small" type="text" maxlength="255" value="<?php echo $_GET['partner_business_years']; ?>"/>

Is this considered a ridiculous approach? If I used JavaScript, I could use an iterator to run through all the fields in one little loop, instead of individually populating each value attribute with PHP. But server-side seems to be the right place to do this since the form doesn't otherwise rely on JavaScript.

The next question: I have some Yes/No questions in radio button form. The query string will therefore contain values like will_relocate=yes. In my mind, I want to just say "Select the appropriate radio based on the query string", but there's no real concept of selecting for radios... there's a shared name with different value options.

Here's the original HTML:

  <input id="relocate_1" name="will_relocate" class="element radio" type="radio" value="yes" />
Yes

  <input id="relocate_2" name="will_relocate" class="element radio" type="radio" value="no" />
  No

I can get it working by doing something like this:

<input id="relocate_2" name="will_relocate" class="element radio" type="radio" value="no" <?php if($_GET['will_relocate'] && $_GET['will_relocate'] == "no") { echo 'checked'; } ?>/>

(with a matching one for "yes"... and as many pairs of these as needed)

But it strikes me as hideous. I'm just a hack at PHP, and I'm sure I could break this out into a function, but I would still have a pair of <?php selectRadio('will_relocate') ?> - type calls throughout my document, which is barely better.

Any ideas? Is my approach just completely nasty from the get-go? Should I use JavaScript after all?

I'm open to JavaScript-based suggestions for form re-populating, but not as the sole validator (I don't have and wouldn't choose that option).


texts: Disable execution of parts of the code based on user's choice C++

texts:
I am working on the small program for data acquisition where the data is written to log file and the clients can listen to data broadcasted over socket.

What I would like to achieve is to give the user some control over the program, to decide, if the data logging or the socket server should be started or not, for now I am using the console arguments for those user-program interaction. The problem is that if the user decides not to use the socket server, then multiple lines of the code in different parts of the program should not be executed (the socket object should not be constructed and non of it's methods should be executed). This easily leads to the problems, as all executions of the methods need to have the constraints. If I forget any, it leads to problems

Here you can see my actual implementation of main, which checks the user's inputs and executes code accordingly:

int main(int argc, char *argv[])
{
    std::string port = "27013"; // default port for socket, used if not specified different in console argument
    bool socketsActivated = true; // default value
    bool logActivated = true; // default value
    std::unique_ptr<ServerCommunication> server; // socket broadcaster object
    std::unique_ptr<ServerEcho> echo; // socket echoing object
    std::unique_ptr<FileOperations> traceFile; // Trace logging object

    for (int i = 1; i < argc; ++i) {
        if (std::string(argv[i]) == "--port") {
            if (i + 1 < argc) { // Make sure we aren't at the end of argv!
                port = std::string(argv[i++]); // Increment 'i' so we don't get the argument as the next argv[i].
            }
            else { // There was no port argument
                std::cerr << "--port option requires one argument." << std::endl;
                return 1;
            }
        }
    }

    for (int i = 1; i < argc; ++i) {
        if (std::string(argv[i]) == "--nosocket")
            socketsActivated = false;
    }

    for (int i = 1; i < argc; ++i) {
        if (std::string(argv[i]) == "--nolog")
            logActivated = false;
    }

    if (socketsActivated){
        server= std::make_unique<ServerEcho>(port);
        echo = std::make_unique<ServerEcho>("27014");
    }

    if (logActivated)
        traceFile.reset(new FileOperations());

    while (!_kbhit()) // Till the key was pressed
    {
        Sleep(25); // lower the load on CPU

        if (socketsActivated){
            server->update();
            echo->update();
        }
    }
    return 0;
}

It is error-prone as if the code will get more complex additional parts of the program will need to be nested if the case requires, what will easily leads to problems...

Is there a better, easier approach for it? The preprocessor directives will not help here.


texts: How should I structure my Unit tests for minimal Asserts?

texts:
I always see comments about how a Unit Test should only be testing one piece of functionality. For the most part, I definitely agree with that assessment. However, I'm working on testing a method right now that has me pondering if being laxer on this ideal would be a better thing, so I'm curious to everyone's opinions.

The method that I'm testing is one that gathers Messages created between a user-defined date range, and groups them by Date, with totals of each type of Message per day. (Request, Offer, Dialog, and Referral).

So for a range of two days (for simplicity), I'll return an IEnumerable<MessageDay>, where MessageDay is defined as such:

public class MessageDay() {
    public DateTime Date { get; set; }
    public int Requests { get; set; }
    public int Offers { get; set; }
    public int Dialogs { get; set; }
    public int Referrals { get; set; }
    public int Total {
        get {
            return this.Requests + this.Offers + this.Dialogs + this.Referrals;
        }
    }
}

I have my Mock setup for my unit test with several of each type of Message, ranging from DateTime.MinValue, DateTime.Now, and DateTime.MaxValue.

Should I create a Unit Test with the same parameters going into the method I'm testing repeatedly? (i.e. first test will test a count of the days, second test will test the total Requests for day 1, etc for each type of Message, for each date)

I'm thinking that having so many tests (up to 13 per date range with 4 different date parameter possibilities) would be ridiculous, however I would like to know the standard, accepted way to do this.

EDIT
Here is my Mock data that I have set up:

[TestInitialize()]
public void TestInitialize() {
    var mock = new Mock<IReportingRepository>();
    var now = DateTime.Now;

    mock.Setup(m => m.Messages).Returns(new Message[] {
        new Request { CreatedOn = now },
        new Request { CreatedOn = DateTime.MinValue },
        new Request { CreatedOn = DateTime.MaxValue },
        new Offer { CreatedOn = DateTime.MinValue },
        new Offer { CreatedOn = DateTime.MinValue },
        new Offer { CreatedOn = DateTime.MaxValue },
        new Dialog { CreatedOn = now },
        new Dialog { CreatedOn = DateTime.MaxValue },
        new Referral { CreatedOn = now },
        new Referral { CreatedOn = DateTime.MinValue }
    }.AsQueryable());

    controller = new ReportingController(mock.Object);
}

This would be along the lines of my "fewest number of tests":

[TestMethod]
public void CanFindAllCounts() {
    var result = (MessageResponse)controller.GetMessageAnalytics(new MessageRequest()).Data;

    Assert.AreEqual(3, result.Days.Count());

    var day = result.Days.FirstOrDefault();
    Assert.AreEqual(4, day.Total);
    Assert.AreEqual(1, day.Requests);
    Assert.AreEqual(2, day.Offers);
    Assert.AreEqual(0, day.Dialogs);
    Assert.AreEqual(1, day.Referrals);

    day = result.Days.Where(d => d.Date.Date == DateTime.Now.Date).FirstOrDefault();
    Assert.AreEqual(3, day.Total);
    Assert.AreEqual(1, day.Requests);
    Assert.AreEqual(0, day.Offers);
    Assert.AreEqual(1, day.Dialogs);
    Assert.AreEqual(1, day.Referrals);

    day = result.Days.Last();
    Assert.AreEqual(3, day.Total);
    Assert.AreEqual(1, day.Requests);
    Assert.AreEqual(1, day.Offers);
    Assert.AreEqual(1, day.Dialogs);
    Assert.AreEqual(0, day.Referrals);
}

The other extreme would of course be a test for each of those Asserts. Being that I'm using Moq, it's not a huge deal and would run quickly, but I just feel that it's overkill.


texts: spark takes long time for checking an array of items present in another array

texts:
I am new to spark. I have two dataframes df1 and df2. df1 has three rows. df2 has more than few million rows. I want to check whether all items in df2 are in transaction of df1, if so sum up the costs. Example as follows:

 df1 = spark.createDataFrame(
 [(1, [(1), (4), (2) ,(3)])],
 ("id", "transaction")
 )

 df2 = spark.createDataFrame(
 [([ (1),(2),(3)], 2.0), ([(5),(2),(3)], 1.0) ],
 ("items", "cost")
 )

Desired Result is:

 id   transaction score
  1    [1,4,2,3]    2.0

My Current code is:

out=df1.crossJoin(df2)

@udf('boolean')
def check(trans,itm):
   itertrans = iter(trans)
   return all(i in itertrans for i in itm)

 out.groupby('id','transaction')\
    .agg(sum_(when(check('transaction','items'),col('cost'))).alias('score'))\
    .show()

The other solution which i have:

 costs = (df1
# Explode transaction
.select("id", explode("transactions").alias("item"))
.join(
    df2
        # Add id so we can later use it to identify source
        .withColumn("_id", monotonically_increasing_id().alias("_id"))
         # Explode items
        .select(
            "_id", explode("items").alias("item"),
            # We'll need size of the original items later
            size("items").alias("size"), "cost"),
     ["item"])
 # Count matches in groups id, items
 .groupBy("_id", "id", "size", "cost")
 .count()
 # Compute cost
 .groupBy("id")
 .agg(sum_(when(col("size") == col("count"), col("cost"))).alias("score")))
  costs.show()

with 500,000 rows of df2, crossJoin method produced results quicker (in 6 min) when compared to the explode and join soution (which took 15 mins).

with 900,000 rows of df2, both solution run for hours without results.
I run  the program in  standalone mode.

Questions:

How can i improve the speed? Any other solution?
   if i convert to rdd and run in clutser, will the process speeds up?
   How to convert to rdd?(i tried but don't know how to convert the group by and aggreagta part)

Any help would be great.


texts:
Here is a simple Guessing Game I implemented in Haskell

import System.Random
import Text.Read

main :: IO ()
main = do
  putStrLn "I am guessing a value between 1 to 100"
  guess <- (randomIO :: IO Int)
  playWith (guess `mod` 100)
  putStrLn "Play again? (Y/N)"
  response <- getLine
  if response == "Y" then
    main
  else
    return ()

playWith :: Int -> IO ()
playWith n = go 5
  where
  go 0 = putStrLn "You loose!"
  go n = do
    putStr "Enter your guess: "
    guess <- readUntilValid
    if n == guess then
      putStrLn "You win!"
    else
      if n < guess then
          putStrLn "Too large!" >> go (n-1)
      else
          putStrLn "Too small!" >> go (n-1)

readUntilValid :: IO Int
readUntilValid = do
  s <- getLine
  case (readMaybe s :: Maybe Int) of
    Nothing -> putStr "Please enter a valid guess:" >> readUntilValid
    Just x -> return x

Is there something I can (or should) do to prevent the usage of goto like recursion? Maybe I could use something from Control.Monad?


texts:
I have a fairly ugly controller method I would like to refactor / extract. I can only test this in an integration-type test which kind of signals a code smell.

The method processes the form and needs to do one of 5 things, depending on which button was pressed

if submitted and valid (button 1) => update some values on the entity and re-render the form
if submitted and valid (button 2) => perform another controller action that shows a .pdf print of the entity
if submitted and valid (button 3) => save entity and redirect
if not submitted or not valid => render form (plus errors)

In code it looks kind of like this:

protected function processForm(Request $request, MyEntity $entity)
{
    $form = $this->createForm(new MyEntityType, $entity);

    if ($form->handleRequest($request)->isValid()) {

        $alteredEntity = SomeClass:performStuffOnEntity($entity);

        if ($form->get('button1')->isClicked()) {
            $form = $this->createForm(
                new MyEntityType, $alteredEntity
            );
        }
        else if ($form->get('button2')->isClicked()) {
            return $this->pdfPreview($alteredEntity);
        }
        else if ($form->get('button3')->isClicked()) {
            return $this->persistAndRedirectToEntity(
                $alteredEntity
            );
        }
    }

    return $this->render(
        'MyBundle:MyEntity:new.html.twig', array(
            'form' => $form->createView(),
    ));
}

There are actually two buttons like button1; I left one out for brevity of the example.

Ideas:

I have tried to extract this into a EntityFormWizard of some sort but this ended up as a cluttered Object with too many dependencies (Router, Templating, Form) which was also a pain to test.
Using FormEvents I wanted to extract at least the altering of the entity depending on which button was pressed into a FormEventListener, but the only place where I can alter the Entity is the FormEvents::PRE_SET_DATA event, but in there I have problems figuring out which button was clicked.

Do I have to live with my integration test for this behavior or is there a way to extract it and test it with a unit test?


texts: Simple builder pattern implementation for building immutable objects

texts:
This is a builder pattern implementation to build immutable Person objects:

Person class

public final class Person {

    // All are set to final to make Person Immutable
    private final int id;
    private final String name;
    private final String surname;
    private final boolean isOccupied;

    // Constructor is private, so that only static
    // PersonBuilder can initiate the Person class instance
    private Person(PersonBuilder builder) {
        this.id = builder.getId();
        this.name = builder.getName();
        this.surname = builder.getSurname();
        this.isOccupied = builder.isOccupied();
    }

    public static class PersonBuilder {

        // Member variables of PersonBuilder are temporary storage
        // to create Immutable Person class instance
        private int id;
        private String name;
        private String surname;
        private boolean isOccupied;

        PersonBuilder() { }

        // The only method to initiate Person class
        Person build() {
            return new Person(this);
        }

        // Multiple Constructors for each member variable
        public PersonBuilder id(int id) {
            this.id = id;
            return this;
        }

        public PersonBuilder name(String name) {
            this.name = name;
            return this;
        }

        public PersonBuilder surname(String surname) {
            this.surname = surname;
            return this;
        }

        public PersonBuilder setOccupied(boolean isOccupied) {
            this.isOccupied = isOccupied;
            return this;
        }

        // getters, these will be used in private constructor
        // of Person class
        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        public String getSurname() {
            return surname;
        }

        public boolean isOccupied() {
            return isOccupied;
        }
    }

    // getters
    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getSurname() {
        return surname;
    }

    public boolean isOccupied() {
        return isOccupied;
    }

    @Override
    public String toString() {
        return String.format(
                "Id:\t\t%d\nName:\t\t%s\nSurname:\t%s\nIsOccupied:\t%s\n"
                , id, name, surname, isOccupied);
    }

}

Person demo

public class PersonDemo {

    public static void main(String[] args) {
        // PersonBuilder instance
        Person.PersonBuilder builder = new Person.PersonBuilder();

        // builder builds the instance
        builder.name("Levent").surname("Divilioglu").id(666).setOccupied(true);

        // Immutable Person object is initiated with build() method
        Person person = builder.build();

        System.out.println(person);
    }

}

Demo output

Id:           666
Name:     Levent
Surname:  Divilioglu
IsOccupied:   true

I did write this implementation to learn the GoF builder pattern. Immutability is important for thread-safety, thus set the class and it's members final. I also set the Person constructor private to guarantee that it is only instantiated with inner class method, and only once. On each build() method, a new unique Person instance will be created.

I'm aware that builder patter is used for classes that have a lot of many member variables but I did only used 4 member variables for the simplicity.


texts: Code review needed for my Prime factorization code

texts:
Below is the code for knowing all the prime factors of a number. I think there must be some better way of doing the same thing. Also, please tell me if there are some flaws in my code.

def factorize(num):
    res2 = "%s: "%num
    res = []
    while num != 1:
        for each in range(2, num + 1):
            quo, rem = divmod(num, each)
            if not rem:
                res.append(each)
                break
        num = quo
    pfs = set(res)
    for each in pfs:
        power = res.count(each)
        if power == 1:
            res2 += str(each) + " "
        else:
            res2 += str(each) + '^' + str(power) + " "
    return res2


texts: pyCMD; a simple shell to run math and Python commands

texts:
I made a command line in Python.
Before I go on and add more commands, is my program made well?
I don't like the huge amount of "if" statements in it. But I don't know a better way to do it. (JSON may be used later this is why I have it included)
Here's the code:
import time
import json
print("Welcome to pyCMD, user\n")
time.sleep(0.2)
input("Press enter to start\n")
time.sleep(0.2)

def SavetoDisk(data, file):
    with open(file, 'w') as outfile:
        json.dump(data, outfile)

def ReadfromDisk(file):
    with open(file) as json_file:
        data = json.load(json_file)
    return data
print('Starting command line, use "help . ." for help')
running = True
commandList = "add | sub | mult | div | exp | tetrate | python"
while running:
    try:
        userInput = input(': ')
        tokens = userInput.split()
        command = tokens[0]
        args = [(token) for token in tokens[1:]]
    except: print("unknown input error")
    try:
        arg1, arg2 = args
    except ValueError:
        print('Too many or too little args, 2 args required, if you want to not use an arg, use a "."')

    if command == "add":
        print(float(arg1) + float(arg2))

    if command == "sub":
        print(float(arg1) - float(arg2))

    if command == "mult":
        print(float(arg1) * float(arg2))        #math commands

    if command == "div":
        print(float(arg1) / float(arg2))

    if command == "exp":
        print(float(arg1) ** float(arg2))

    if command == "tetrate":
        for x in range(int(arg2)):
            arg1 = float(arg1) * float(arg1)
        print(arg1)

    if command == "python":
        exec(open(arg1).read())

    if command == "help":
        if arg1 == '.':
            if arg2 == '.':
                print('To see help about a command, type: "help [command] ." for list of commands type: "help command list"')

        if arg1 == 'command':
            if arg2 == 'list':
                print(commandList)

        if arg1 == 'add':
            print("Add: \n Description: Adds 2 numbers \n Syntax: add [num1] [num2]")

        if arg1 == 'sub':
            print("Sub: \nDescription: Subtracts 2 numbers \n Syntax : sub [num1] [num2]")

        if arg1 == 'mult':
            print("Mult: \nDescription: Multiplies 2 numbers \n Syntax : mult [num1] [num2]")

        if arg1 == 'div':
            print("Div: \nDescription: Divides 2 numbers \n Syntax : div [num1] [num2]")

        if arg1 == 'exp':
            print("Exp: \nDescription: Raises 1 number by another \n Syntax : exp [num1] [num2]")

        if arg1 == 'tetrate':
            print("Tetrate: \nDescription: Tetration \n Syntax : tetrate [num1] [num2]")

        if arg1 == 'python':
            print("Python: \nDescription: Runs a python script \n Syntax : python [path/to/program.py] .")


texts: Data type detection for a CSV file parser

texts:
I am building a CSV file parser, and in order to get the appropriate Object to represent different data types found on the parsed files, I wrote the following function:

public static Object stringToDataType(String valueAsString) throws ParseException{
    // detections ordered by probability of occurrence in Buffer_Bank.
    String decimalPattern = detectDecimal(valueAsString);
    if(decimalPattern != null){
        return stringToBigDecimal(valueAsString, decimalPattern);
    }else{
        String integerPattern = detectInteger(valueAsString);
        if(integerPattern != null){
            return stringToBigInteger(valueAsString);
        }else{
            String datePattern = detectDate(valueAsString);
            if(datePattern != null){
                return stringToDate(valueAsString, datePattern);
            }else{
                // value is a String... nothing else to do!
                return valueAsString;
            }
        }
    }
}

In order to call the appropriate 'casting' methods (stringToDate, stringToBigInteger, stringToBigDecimal), I need to use the specific pattern string that gets returned when detecting if a particular value is of that type.
Hence, the pattern value gets used for routing to the appropriate function, and also as an argument in that function call.

To make this method logic 'flatter', I could avoid passing the pattern as an argument, and calling the pattern detection method (detectDecimal, detectInteger, detectDate) again from within the 'casting' method, but that would lead to parsing the same value two times, which seems wasteful at best.

So, is this the best way this method can be written without getting to call the detection methods twice?

EDIT

Here are the detectDate and stringToDate methods, as requested (the methods for BigInteger and BigDecimal are very similar). Please let me know if I need to post anything else:

private static String detectDate(String dateString) {
    for (String regexp: DATE_FORMAT_REGEXPS.keySet()) {
        if(dateString.toLowerCase().matches(regexp)) {
            return DATE_FORMAT_REGEXPS.get(regexp);
        }
    }
    return null; // value is not a date
}

public static Date stringToDate(String valueAsString, String format) throws ParseException{
    SimpleDateFormat dateFormat = new SimpleDateFormat(format);
    Date date = dateFormat.parse(valueAsString);
    return date;
}


texts:
I made a stack monad that lets one manipulate and control values on a stack.

I want to know if it's correct (it seems correct), how to make it faster, and how I could detect stack overflows without carrying around the stack size and checking against it (I've heard about guard pages but I have no idea how I'd use them with Haskell).

{-# LANGUAGE RankNTypes #-}
module Main where

import Data.IORef

import Foreign.Ptr
import Foreign.Storable
import Foreign.Marshal.Alloc

import Control.Exception ( bracket )

import System.IO.Unsafe

newtype StackRef s a = StackRef (Ptr a)

data Stack = Stack (Ptr ())
newtype StackMonad s a = StackMonad (Stack -> IO (Stack, a))

instance Monad (StackMonad s) where
 return x = ioToStackMonad (return x)
 (StackMonad m) >>= f = StackMonad $ \stack -> do
   (newStack, x) <- m stack
   let (StackMonad g) = f x
   g newStack

runStackWithSize :: Int -> (forall s. StackMonad s a) -> a
runStackWithSize stackSize (StackMonad f) = unsafePerformIO $
 bracket (mallocBytes stackSize) free $ \theStack -> do
  (_, a) <- f (Stack theStack)
  return a

-- | 1024 bytes is the usual size for a stack
runStack :: (forall s. StackMonad s a) -> a
runStack = runStackWithSize 1024

newStackRef :: Storable a => a -> StackMonad s (StackRef s a)
newStackRef value = StackMonad $ \(Stack topOfStack) -> do
 let ptr = castPtr (alignPtr topOfStack (alignment value))
 poke ptr value
 return (Stack (plusPtr ptr (sizeOf value)), StackRef ptr)

ioToStackMonad :: IO a -> StackMonad s a
ioToStackMonad action = StackMonad $ \ptr -> do
 a <- action
 return (ptr, a)

writeStackRef :: Storable a => StackRef s a -> a -> StackMonad s ()
writeStackRef (StackRef p) val = ioToStackMonad (poke p val)

readStackRef :: Storable a => StackRef s a -> StackMonad s a
readStackRef (StackRef p) = ioToStackMonad (peek p)

{- |
 The type hackery means that pointers to the old stuff isn't reachable,
 therefore it's okay to pop the stack pointer.
-}
stack :: (forall s. (forall b. StackRef t b -> StackRef s b) -> StackMonad s a) -> StackMonad t a
stack f = let (StackMonad s) = f (\(StackRef p) -> StackRef p) in StackMonad $ \old_ptr -> do
 (_, state) <- s old_ptr
 return (old_ptr, state)

stack_ :: (forall s. (forall b. StackRef t b -> StackRef s b) -> StackMonad s ()) -> StackMonad t ()
stack_ f = let (StackMonad s) = f (\(StackRef p) -> StackRef p) in StackMonad $ \old_ptr -> do
 _ <- s old_ptr
 return (old_ptr, ())

x :: Int
x = runStack $ do
 a <- newStackRef 5

 c <- stack $ \lift1 -> do
  b <- newStackRef 1

  let liftedA = lift1 a
  aValue <- readStackRef liftedA
  writeStackRef liftedA 6
  bValue <- readStackRef b
  return (aValue + bValue)
 newAValue <- readStackRef a
 return (c + newAValue)

main = print x


texts: Generating 3D voxel terrain with Perlin Noise

texts:
I've created this simple 3D voxel terrain generator using Perlin Noise. I have a few concerns about it though.

Is there any way to make it more performant? It currently takes ~1.5 seconds to generate a 200x200 map.
Am I splitting up the different "jobs" of the generator correctly?
Is my general code style good?

using UnityEngine;

/// <summary>
/// Terrain generator.
/// </summary>
public class TerrainGenerator : MonoBehaviour
{
    public GameObject cube;
    public int worldWidthX;
    public int worldWidthZ;

    public float lowerNoiseScaleValue;
    public float upperNoiseScaleValue;

    public float lowerNoiseScaleModifierValue;
    public float upperNoiseScaleModifierValue;

    private float noiseScale;
    private float noiseScaleModifier;

    /// <summary>
    /// Generates the cubes as children of a GameObject.
    /// </summary>
    public void InitalizeCubes()
    {
        for(float x = 0; x <= this.worldWidthX; ++x)
        {
            for(float z = 0; z <= this.worldWidthZ; ++z)
            {
                GameObject cube = Instantiate(
                    this.cube,
                    new Vector3(x, 0, z),
                    this.cube.transform.rotation
                ) as GameObject;

                cube.transform.parent = this.transform;
            }
        }
    }

    /// <summary>
    /// Sets the color of the cube based on the cube's height.
    /// </summary>
    /// <param name="cube">Cube.</param>
    /// <param name="cubeHeight">Cube height.</param>
    public void SetCubeHeightColor(Transform cube, float cubeHeight)
    {
        cube.renderer.material.color = new Color(cubeHeight / 5, cubeHeight, cubeHeight / 5);
    }

    /// <summary>
    /// Applies a height value to the transform of a cube.
    /// </summary>
    /// <param name="cube">Cube.</param>
    /// <param name="cubeHeight">Cube height.</param>
    public void ApplyHeightToCube(Transform cube, float cubeHeight)
    {
        int newHeight = Mathf.RoundToInt(cubeHeight * this.noiseScaleModifier);
        Vector3 newPosition = new Vector3(cube.transform.position.x, newHeight, cube.transform.position.z);
        cube.transform.position = newPosition;
    }

    /// <summary>
    /// Updates the positions of the cubes by giving
    /// each cube a specific perlin noise value,
    /// coloring them, and finally, applying the height
    /// values to the transform.position's of the cubes.
    /// </summary>
    public void GenerateCubes()
    {
        foreach(Transform cube in transform)
        {
            float noiseScaleAddition = Random.Range(this.noiseScale / 10, this.noiseScale / 9);
            float cubeHeight = Mathf.PerlinNoise(
                (cube.transform.position.x / (this.noiseScale + noiseScaleAddition)),
                (cube.transform.position.z / (this.noiseScale + noiseScaleAddition))
            );
            SetCubeHeightColor(cube, cubeHeight);
            ApplyHeightToCube(cube, cubeHeight);
        }
    }

    /// <summary>
    /// Start this instance.
    /// </summary>
    void Start()
    {
        this.noiseScale = Random.Range(this.lowerNoiseScaleValue, this.upperNoiseScaleValue);
        this.noiseScaleModifier = Random.Range(this.lowerNoiseScaleModifierValue, this.upperNoiseScaleModifierValue);

        this.InitalizeCubes();
        this.GenerateCubes();
        Screen.lockCursor = true;
    }
}

For those who are curious, here are a few pictures of sample terrain:

If you want to critique or suggest changes to the algorithm, I'm open to them.


texts:
The following script makes an image pulse in Unity by fluctuating its alpha channel.  However, I feel like there is a lot of duplicate code in the update method.  How can I clean up that code to have it not repeat itself with +-, true false, etc.?

using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Image))]
public class Pulse : MonoBehaviour
{
    private Image image;

    [Tooltip("How long in seconds it takes to complete a pulse")]
    [SerializeField]
    [Range(0.0f, 60.0f)]
    private float time = 2.0f;

    [Tooltip("Minimum alpha to pulse to")]
    [SerializeField]
    [Range(0.0f, 1.0f)]
    private float minAlpha = 0.0f;

    [Tooltip("Maximum alpha to pulse to")]
    [SerializeField]
    [Range(0.0f, 1.0f)]
    private float maxAlpha = 1.0f;

    private bool alphaIncreasing = false;

    private void Awake()
    {
        image = GetComponent<Image>();
    }

    void Update()
    {
        var color = image.color;
        float alphaChange = Time.deltaTime / time / 2.0f;
        if (alphaIncreasing)
        {
            color.a += alphaChange;
            if (color.a >= maxAlpha)
            {
                color.a = maxAlpha;
                alphaIncreasing = false;
            }
        }
        else
        {
            color.a -= alphaChange;
            if (color.a <= minAlpha)
            {
                color.a = minAlpha;
                alphaIncreasing = true;
            }
        }
        image.color = color;
    }
}


texts: Finding a sum of unique triplet that is close to a given number in an array

texts:
I asked one question on code review yesterday about my code style, logic and readability of code. Hence, today I kept all those suggestions in mind while solving a new problem question.

The question is such: Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

For example: given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

This is my solution:

 public int threeSumClosest(int[] num, int target) {
    if(num.length < 3) {
        return 0;
    }
      Arrays.sort(num);
    int tempSum = Math.abs( target - ( num[0] + num[1] + num[2] ));
    int result = num[0] + num[1] + num[2];

    for (int index = 0; index < num.length - 1; index++) {
        int j = index + 1;
        int k = num.length-1;
        while (j < k){
            int newSum = Math.abs( target - ( num[index] + num[j] + num[k] ) );
            if( newSum == 0 ) {
                return ( num[index] + num[j] + num[k] ) ;
            }
            else if ( num[index] + num[j] + num[k] < target ) {
                if( newSum < tempSum ) {
                    tempSum = newSum;
                    result = num[index] + num[j] + num[k];
                }

                j++;
            }
            else {
                if( newSum < tempSum ) {
                    tempSum = newSum;
                    result = num[index] + num[j] + num[k];
                }
                k--;
            }
        }//end of while loop
    }// end of for loop
    return result;
}

It would be great to hear back if I need to make further improvements. Any help will be highly appreciated. Also, Is there an approach which can solve this problem in less than \$O(n^2)\$.


texts:
I just started to learn Elixir and to train on Codewars.
I solved this kata but I'm not very satisfied of my code and I have no clue (literally) how to improve it.
Recursion seems the way to go here, but I'm convinced the code can be optimized a little more.

Here is the full problem :

  The input is a string str of digits. Cut the string into chunks of
  size sz (ignore the last chunk if its size is less than sz).

  If a chunk represents an integer such as the sum of the cubes of its
  digits is divisible by 2, reverse it; otherwise rotate it to the left
  by one position. Put together these modified chunks and return the
  result as a string.

Could you help me please ?

defmodule Revrot do
def revrot(str, sz) do
    if str == "" or sz <= 0 or String.length(str) < sz do
      ""
    else
      chunk = str |> String.slice(0,sz)
      t = chunk |> String.to_integer |> Integer.digits |> Enum.reduce(0, fn(x, acc) -> (:math.pow(x,3) |> round) + acc end)
      temp = case (rem t,2) do
        0 -> chunk |> String.reverse
        _ -> String.slice(chunk, 1, sz-1) <> String.first(chunk)
      end
      temp <> revrot(String.slice(str,sz..-1), sz)
    end
  end
end


texts: Writing line item information from multiple tables

texts:
The following is part of a personal budgeting program I'm writing.

This code pulls line item information from multiple tables and writes it into an array and then displays the information by transid => family => category => lineItems. Everything works, and I get the results I want out of it. I want to know if there is a more efficient way to accomplish this task.

Since this is a personal program, I'm only asking so that I can improve my coding abilities.

<?php

include ('../cfg/connect.php');

$s = " : ";
$br = "
";
$ul = "
";
$li = "
";
$_ul = "
";
$_li = "
";

$data = [];
$itemCount = 0;
$arrayItemCount = 0;

$categoryQry = "SELECT a.itemQty, b.transDate, b.transID, b.amount, a.itemPrice, a.itemCategory, c.catFamily, a.itemName, a.itemSource FROM budget.lineItems AS a JOIN budget.quickEntry AS b ON a.transID = b.transID JOIN budget.categories AS c ON a.itemCategory = c.catName WHERE b.processed = 'y' ORDER BY c.catFamily, c.catName, b.transDate";
$categories = $conn->prepare ($categoryQry);
$categories->execute ();
$categories->store_result ();
$categories->bind_result ($itemQty, $transDate, $transID, $totalPrice, $itemPrice, $category, $family, $itemName, $source);

while ($categories->fetch ()) {

    if (!isset($data[$transID]['amount'])) {
        $data[$transID]['amount'] = 0;
    }
    if (!isset($data[$transID]['line'])) {
        $data[$transID]['line'] = '';
    }
    if (!isset($data[$transID]['line'][$family]['amount'])) {
        $data[$transID]['line'][$family]['amount'] = 0;
    }
    if (!isset($data[$transID]['line'][$family]['line'])) {
        $data[$transID]['line'][$family]['line'] = '';
    }
    if (!isset($data[$transID]['line'][$family]['line'][$category]['amount'])) {
        $data[$transID]['line'][$family]['line'][$category]['amount'] = 0;
    }
    if (!isset($data[$transID]['line'][$family]['line'][$category]['line'])) {
        $data[$transID]['line'][$family]['line'][$category]['line'] = '';
    }

    $itemCount++;

    $qtyPrice = $itemPrice * $itemQty;
    $data[$transID]['amount'] += $qtyPrice;
    $data[$transID]['transDate'] = $transDate;
    $data[$transID]['source'] = $source;
    $data[$transID]['line'][$family]['amount'] += $qtyPrice;
    $data[$transID]['line'][$family]['line'][$category]['amount'] += $qtyPrice;
    $data[$transID]['line'][$family]['line'][$category]['line'][$itemName] = ['itemQty' => $itemQty, 'itemPrice' => $itemPrice];
}

foreach ($data as $transID => $transValue) {
    echo $transID .$s.$transValue['transDate'].$s.$transValue['source'].$s.$transValue['amount']. $ul;
    foreach ($transValue['line'] as $category => $categoryValue) {
        echo $li . $category .$s.$categoryValue['amount']. $ul;
        foreach ($categoryValue['line'] as $line => $lineValue) {
            echo $li . $line .$s.$lineValue['amount']. $ul;
            foreach ($lineValue['line'] as $item => $details) {
                echo $li . $item .$s . $details['itemQty'] . $s . $details['itemPrice'] . $_li;
            }
            echo $_ul . $_li;
        }
        echo $_ul . $_li;
    }
    echo $_ul . $br;
}


texts:
This is a working example that I am trying to improve.

Throughout the application I am working on one of the requirements was to have tooltips everywhere.  However the customer wanted the ability to see a "Summary" of these tooltips and be able to manage them from a single location.

What I ended up doing is creating a new class called FormatToolTip.js

function FormatToolTip() {
    var self = this;
    amplify.request.define("toolTipListing", "ajax", {
        url: "resources/prototype/tooltips.json",
        dataType: "json",
        type: "GET"
    });
    self.ToolTipId = "ToolTipId";
    self.allToolTips = "ToolTips";
    self.init = function () {
        amplify.request({
            resourceId: "toolTipListing",
            success: function (data) {
                amplify.store(self.allToolTips, data.toolTips);
            },
            error: function () {
            }
        });
    };

self.buildToolTip = function (helpId) {
    var toolTipList = amplify.store(self.allToolTips);
    for (var i = 0; i < toolTipList.length; i++) {
        var val = toolTipList[i];
        if (helpId == val.id) {
            text = val.text;
            return text;
        }
    }
    return amplify.store(self.ToolTipId);
};
self.setToolTipId = function (toolTipId) {
    if (toolTipId != undefined || toolTipId != null) {
        amplify.store(self.ToolTipId, toolTipId);
    }
};
self.init();
}

I wanted everything to be based off a class I assign to the element.   Here is an example of the format I used.

From there it can be initialized.

To polish off the look and feel I added some CSS and a background image for the element.

.withToolTip{
    background-image:url("images/help.png");
    background-repeat: no-repeat;
    background-position: center;
    background-size: 20px;
    width: 20px;
    height: 20px;
    display: inline-block;
    vertical-align: middle;
    padding-left: 10px;
}

I am looking to improve on my code. So suggestions would be awesome.


texts: Naive Solver of Matrix with Periodic Boundary Conditions Feedback

texts:
I am creating an \$O(n)\$ solver for an \$Ax = b\$ system where \$A\$ has the form
\$
A = \begin{pmatrix}
a_1 &  b_1   &&&d_{u}\\ c_1 &  a_2   & b_2\\& \ddots & \ddots & \ddots\\&   &  c_{n-2}&a_{n-1}& b_{n-1}\\ d_{l} &&&c_{n-1}& a_{n}
\end{pmatrix}
\$
To do this, I wrote a basic function that just performs Gaussian elimination. I was wondering if there are any immediate ways to improve the code below. My main goal is obviously speed, so I would like to know of any tricks that would minimize memory usage (while preserving \$A\$) and the number of computations being performed. I have already made \$A\$ into a sparse matrix which helped a fair bit already. Also to note, that even though the code is in python, it's not written in a pythonic way because I typically develop initial code (for easier debugging) in python before writing the final version in C.
def solve_periodic_sparseA_vectB(A, b, results, corner_upper, corner_lower):
    n = b.shape[0]
    results[0] = b[0]
    results[n - 1] = b[n - 1]
    supra_diag = A[2].copy()
    last_col = np.zeros(n - 1)  # excludes final val main
    last_col[0] = corner_upper
    last_col[n - 2] = supra_diag[n - 2]
    last_row_val = corner_lower
    current_main = A[1][0]
    next_main = A[1][1]
    last_main = A[1][n - 1]

    for i in range(n - 2):
        # divide by pivot
        ci = current_main
        results[i] = results[i] / ci
        supra_diag[i] = A[2][i + 1] / ci
        last_col[i] /= ci
        # -aRi + Ri+1 --> Ri+1
        a = A[0][i]
        results[i + 1] = b[i + 1] - a * results[i]
        next_main -= a * supra_diag[i]
        last_col[i + 1] -= a * last_col[i]
        # -aRi + Rn --> Rn
        a = last_row_val
        results[n - 1] = results[n - 1] - a * results[i]
        last_main -= a * last_col[i]
        last_row_val = (A[0][i + 1] if i == n - 3 else 0.0) - a * supra_diag[i]

        current_main = next_main
        next_main = A[1][i + 2]

    i = n - 2
    # divide by pivot
    ci = current_main
    last_col[i] /= ci
    results[i] /= ci
    a = last_row_val
    results[n - 1] -= a * results[i]
    last_main -= a * last_col[i]
    # solve last
    results[n - 1] /= last_main
    # last column
    for i in range(n - 1):
        results[i] -= last_col[i] * results[n - 1]
    # supra-diagonal (final pass)
    for i in range(n - 2, 0, -1):
        results[i - 1] -= supra_diag[i - 1] * results[i]

EDIT:
Example usage would be something like
import numpy as np

if __name__ == '__main__':
    sig = 1.0
    n = 5
    # sparse matrix where rows 0 1 2 are the sub main and supra diagonals respectively
    A = np.r_['0,2', np.full(n, -sig), np.full(n, 1 + 2 * sig), np.full(n, -sig)]
    b = np.arange(n, dtype=np.float64)
    x = np.empty_like(b)
    solve_periodic_sparseA_vectB(A, b, x, -sig, -sig)


texts: Facebook crawler redirect to force displaying own opengraph meta-tags

texts:
For my website, I use the opengraph to send the right data to the crawler.

On the top of all pages on my website, I include the opengraph-script, like this:

if (preg_match("/facebookexternalhit/is", $_SERVER['HTTP_USER_AGENT'])) {
    include("./facebook-crawler.php");
    exit();
}

facebook-crawler.php:

        ## Infos for Crawling
        $server_path                = $_SERVER['REQUEST_URI'];
        $expl_path                  = explode("/", $server_path);
        $page_title                 = $expl_path[1];
        $page_data                  = "";
        $page_path_display          = "";

        if (isset($expl_path[2]) && $expl_path[2]!="") {
            $page_data              = $expl_path[2];
            $page_path_display      = "/".$page_title."/".$page_data;
        } elseif ($page_title!="") {
            $page_path_display      = "/".$page_title."/";
        } else {
            $page_path_display      = "/";
        }

function show_fbmeta_home() {

        global $site_url, $site_url_displayname, $fb_app_id, $fb_admins, $page_path_display, $count_cars, $count_member, $count_ps;

        get_statistics_general();

        $use_title      = "Lunatics Car Club Austria - est. 2014 - {Beta}";
        $use_text       = $count_member." Mitglieder, ".$count_cars." Autos, ".$count_ps."PS. Besuch unsere Website um mehr zu Erfahren!";
        $use_type       = "article";
        $use_pic        = $site_url."/images/home/r32-gruppenbild.jpg";

        $meta_string =
        '<meta property="og:title" content="'.$use_title.'" />
        <meta property="fb:app_id" content="'.$fb_app_id.'"/>
        <meta property="fb:admins" content="'.$fb_admins.'"/>
        <meta property="og:type" content="article" />
        <meta property="og:url" content="'.$site_url.'/" />
        <meta property="og:image" content="'.$use_pic.'" />
        <meta property="og:site_name" content="'.$site_url_displayname.'" />
        <meta property="og:description" content="'.$use_text.'" />
        ';

        return $meta_string;

}

        // Meta Cases
        switch($page_title) {
            case "": case "home":
                echo show_fbmeta_home();
                exit();
            break;
        }

        show_fbmeta_home();

Of course, the script would be extended for each link. If no function for the actual website is present, the home-page would be used.

Is this a legacy-style method, or, could this cause some problems in the future?


texts: Throttling duplicate requests in an HttpModule

texts:
I'm writing a method to throttle duplicate requests taking place within multiple HttpModule instances within a web application.

Currently, I have the following setup:

// Container for semaphores
private static readonly ConcurrentDictionary<string, SemaphoreSlim>
SemaphoreSlims = new ConcurrentDictionary<string, SemaphoreSlim>();

// Wrapper for getting semaphore
private static SemaphoreSlim GetSemaphoreSlim(string id)
{
    return SemaphoreSlims.GetOrAdd(id, new SemaphoreSlim(1, 1));
}

private async Task ProcessImageAsync(HttpContext context)
{
    // `hash` is the request path hashed.
    SemaphoreSlim semaphore = GetSemaphoreSlim(hash);
    await semaphore.WaitAsync();

    try
    {

    // Do awaitable task

    }
    finally
    {
        semaphore.Release();
    }
}

This will work but I have no way of disposing of the semaphore instances since I need to preserve the ConcurrentDictionary and cannot dispose of a semaphore within the Dispose() method for that HttpModule instance as it could be currently waiting in another instance.

By my calculation it would take up ~156 megabytes of memory for 1 million items stored in the dictionary. It's not a massive amount but I'd really like it to be scalable and somehow find a way to clean up after myself.

Is this a sensible pattern and is there a way I can improve on it?


texts: Simple k-means implemention using Python3 and Pandas

texts:
Is there anything I can improve? The distance function is Pearson correlation.

import os
import pandas as pd
import numpy as np
from pandas import Series, DataFrame

def corrpairs(df1, df2):
    """
    Pairwise correlation for columns of two data frames
    :param df1:
    :type df1:
    :param df2:
    :type df2:
    :return:
    :rtype: pandas.core.frame.DataFrame
    """
    return df1.apply(lambda x: df2.corrwith(x))

import pdb
def kcluster(cols, k=4):
    """
    K Means clustering algorithm, applied to columns of a data frame.
    Using Pearson correlation as the distance function.
    :param rows:
    :type rows: pandas.core.frame.DataFrame
    :param k:
    :type k: int
    :return:
    :rtype: list[int]
    """
    cols = cols.astype(float)
    nrow, ncol = cols.shape
    nuclear0 = cols.iloc[:, :k]
    nuclear0.columns = range(k)
    nuclear0 += np.random.randn(np.prod(nuclear0.shape)).reshape(nuclear0.shape)

    correlations = corrpairs(cols, nuclear0)
    groups = correlations.idxmax(axis=0)
    nuclear1 = []
    for i in range(k):
        sub_cols = cols.loc[:, groups == i]
        sub_mean = sub_cols.mean(axis=1)
        nuclear1.append(sub_mean)
    nuclear1 = pd.concat(nuclear1, axis=1)

    while ((nuclear0 - nuclear1).abs() > 0.00001).any().any():
        print(nuclear0)
        print(nuclear1)
        print((nuclear0 - nuclear1).abs())
        nuclear0 = nuclear1
        correlations = corrpairs(cols, nuclear0)
        groups = correlations.idxmax(axis=0)
        nuclear1 = []
        for i in range(k):
            sub_cols = cols.loc[:, groups == i]
            sub_mean = sub_cols.mean(axis=1)
            nuclear1.append(sub_mean)
        nuclear1 = pd.concat(nuclear1, axis=1)

    return groups


texts:
I'm trying to learn C++ (with experience in C and Java, inter alia).
I wrote a program to output a waveform of multiple (superimposed) tones, each varying in pitch.

To execute:

Compilation: g++ -W -Wall -pedantic -std=c++11 main.cpp Tone.cpp
Running: ./a.out
Playing: aplay out -r 44100 -f S16_LE (or S16_BE if you're on a big-endian system)

What can I improve in terms of C++ style and idioms?
I tried to use RAII for my streams and collections, and I tried to avoid news and pointers.

A couple specific questions:

In write_sample, are the cast to (char *) and the sizeof divisions okay?
If not, what's the standard C++ way to write binary data to a file?
Is sizeof really even used in C++, or is this a discouraged C artifact?
What should be const vs. constexpr?
I used a C-style array for octaves in main, instead of std::array<double, 7>, because I like the automatic initializer counting and the iteration is easier.
Is this okay? What would be better?
Does C++ use size_t, int16_t, and the like?

Tone.hpp

#ifndef TONE_H
#define TONE_H

class Tone
{
    private:
        const double sampleRate;
        double s; /* current position along the unit sine curve */
        double lastSample;
    public:
        double getSample() const;
        double nextSample(double frequency, double amplitude);
        Tone(double sampleRate);
};

#endif

Tone.cpp

#include <cmath>
#include "Tone.hpp"

Tone::Tone(double sampleRate) : sampleRate(sampleRate), s(0), lastSample(0)
{
}

double Tone::getSample() const
{
    return this->lastSample;
}

double Tone::nextSample(double frequency, double amplitude)
{
    this->s += frequency / this->sampleRate;
    this->lastSample = amplitude * sin(2*M_PI * this->s);
    return this->lastSample;
}

main.cpp

#include <cmath>
#include <vector>
#include <iostream>
#include <fstream>
#include "Tone.hpp"

void write_sample(std::ostream &stream, double sample);

int main()
{
    constexpr double SAMPLE_RATE = 44100;
    std::vector<Tone> tones;

    // Each of these represents a final octave difference from A4
    const double octaves[] = { -2, 0, 4./12, 7./12, 1, 16./12, 19./12 };
    const size_t count = sizeof(octaves) / sizeof(*octaves);

    std::ofstream outfile("out", std::ofstream::binary);

    // Create a tone generator for each
    for (size_t i = 0; i < count; i++)
    {
        tones.push_back(Tone(SAMPLE_RATE));
    }

    // Set parameters for the output sound
    double duration = 4.0;
    double attack = 1.0;
    double decay = 2.5;
    double amplitude = 0.8;

    // Generate the required samples
    for (double t = 0; t < duration; t += 1 / SAMPLE_RATE)
    {
        // Interpolate with sinusoidal easing up to the attack time, then constant
        double interp = t >= attack ? 1 : sin(M_PI/2 * t);

        // Constant until the decay time, then interpolate linearly out
        double strength = t < (duration - decay) ? 1
            : 1 - (t - (duration - decay)) / decay;

        // Superimpose the samples from each tone generator
        double totalSample = 0;
        for (size_t i = 0; i < count; i++)
        {
            double octave = interp * octaves[i];
            double frequency = 440 * pow(2, octave);
            double sample = tones[i].nextSample(frequency, strength * amplitude);
            totalSample += sample;
        }
        totalSample /= count;

        if (outfile.good())
        {
            write_sample(outfile, totalSample);
        }
        else
        {
            return 1;
        }
    }

    return 0;
}

// Writes a sample to the given output stream as a 16-bit signed integer.
void write_sample(std::ostream &stream, double sample)
{
    int16_t output = (int16_t) (0x7FFF * sample);
    stream.write((char *) &output, sizeof(int16_t) / sizeof(char));
}


texts: Generating double linear sequence in Haskell

texts:
Need some comments on making the below code more effective. I'm pretty new to Haskell.

The sequence in generateSeq is generated by the rule that if x is in the sequence then x*2+1 and x*3+1 are also in the sequence.

getNumberAt gets the n'th number in the (sorted) generated sequence.

The code works but somehow I feel that I'm overcomplicating this. Any pointers are appreciated!

    generateSeq :: Int -> [Integer]
    generateSeq x
        | x == 0 = [1]
        | otherwise = sort $ prev++toAppend
                         where prev = generateSeq(x-1)
                               toAppend = [next*2+1,next*3+1]
                               next = head $ drop(x-1) prev

    getNumberAt :: Int -> Integer
    getNumberAt n = nub(generateSeq n)!!n

    -- Test this!
    main =
       print $ getNumberAt 321


texts:
I have a NodeJS package, staticize, which takes an object of HTTP routes -> file locations, then serves them dynamically on each request.

Could I get some feedback on the latest rewrite of the main file? (Also available on GitHub here)

var fs = require('fs');
var mime = require('mime');

module.exports = function(app, routes) {
    // loop through routes
    for (var index in routes) {
        // closure: route is the HTTP request route, path is the file path
        (function (route, path) {
            app.get(route, function(req, res) {
                // create a readable stream
                var stream = fs.createReadStream(path, {encoding: 'utf8'});

                stream
                    .once('error', function() {
                        res.status(500).end('Server error.');
                        console.error('ERROR (staticize): Could not open readable stream to ' + path);
                    })
                    .once('readable', function() {
                        // create headers
                        var headers = {
                            'Content-Type': mime.lookup(path)
                        };

                        // write head then pipe response
                        res.writeHead(200, headers);
                        stream.pipe(res);
                    });
            });
        })(index, routes[index]);
    }
};

It is called simply like this:

staticize(app, {
    '/foo': '../test/foo/bar.txt',
    '/foo/more': '../test/foo-extra/bar.txt'
});

I've tried to perfect it as much as possible, but I may have overlooked some things.


texts:
I am a young programmer with the ability to learn more. I created a public site where a user can upload multiple pictures at once. The code works successfully and inserts the images into a MySQL database. As I improved the code further by reducing the size of multiple uploaded pictures at once, only one picture was uploaded into the folder and MySQL. Could anyone please help me on this? Is there any style or code to reduce the size of multiple images uploaded by the user?

DS in my code is DIRECTORY_SEPARATOR define in initialize file.

if(isset($_POST['submitImage']))
{
    $file = $_FILES['upload'];
    $errors = array();

    if(empty($file))
    {
        $errors[] = ' The file could not be empty ';
    }
    else
    {
        foreach( $file['name'] as $key => $value )
        {
            $extensions = array("jpeg","jpg","png");
            $file_ext=explode('.',$file['name'][$key]);
            $file_ext=end($file_ext);
            //$file_ext=strtolower(end(explode('.',$file['name'][$key])));

            if(in_array($file_ext,$extensions ) === false)
            {
                $errors[] = "extension not allowed";
            }
            else
            {
                $filetmp = $file['tmp_name'][$key];
                $terget_path = SITE_ROOT.'j2reimage'.DS.'image'.DS;
                $dat = strftime("%Y-%m-%d %H:%M:%S", time());

                if(file_exists($terget_path))
                {
                    //move_uploaded_file( $filetmp, $terget_path.'/'.$file['name'][$key]);
                    mysql_query("insert into 4j2memberimage values ('', $memmem->id,'{$file['name'][$key]}', '$dat')");

                    if(move_uploaded_file($filetmp, $terget_path.'/'.$file['name'][$key] ))
                    {
                        $exe = explode(".", $file['name'][$key]);
                        $ext = $exe[1];
                        $w = 250;
                        $h = 250;
                        $target  = $terget_path.DS.$file['name'][$key];
                        $newcopy = SITE_ROOT.'j2reimage'.DS.'reCopy'.DS.$file['name'][$key];
                        list($w_orig, $h_orig) = getimagesize($target);
                        $scale_ratio = $w_orig / $h_orig;

                        if (($w / $h) > $scale_ratio)
                        {
                            $w = $h * $scale_ratio;
                        }
                        else
                        {
                            $h = $w / $scale_ratio;
                        }

                        $img = "";
                        $ext = strtolower($ext);

                        if ($ext == "gif")
                        {
                            $img = imagecreatefromgif($target);
                        }
                        else if($ext =="png")
                        {
                            $img = imagecreatefrompng($target);
                        }
                        else
                        {
                            $img = imagecreatefromjpeg($target);
                        }

                        $tci = imagecreatetruecolor($w, $h);
                        imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig);

                        if(@imagejpeg($tci, $newcopy, 80))
                        {
                            //return true;
                            $terger_path = $target;
                            //$terger_path = SITE_ROOT.DS.$this->img_path.DS.$this->filename;
                            return unlink($terger_path) ? true : false;
                        }
                    }
                    //end of if file_exists
                }
                else
                {
                    $errors[] = 'Upload extention could not be located';
                }
            }
            //redirect_to('inb.php');
        }
    }
}


texts:
A few weeks ago, I started working with Java. To get more familiar with the language, I decided to make a Tetris clone.

As I finished the Tiles beans class, I went to the Tetromino class, which is basically made of different sets of 4 Tiles objects (I'm grouping them with ArrayLists). Each Tetromino has a different colour and shape.

Would it be better practice to identify what Tetromino I'm trying to make right in the Tetromino class, or should I make a different class for each different kind of Tetromino available, probably extending the Tetromino class?

Example

(Please note that these are just design-illustrative made to represent my question)

Instead of something like:

public class Tetromino {
    private ArrayList<Tiles> tiles = new ArrayList<Tiles>();

    public Tetromino(char shape) {
        switch(shape) {
          case 'L':
             createLShapedTetr();
             break;
          /* etcetera */
        }
    }

    private void createLShapedTetr(){
     /*
      Sets color for bricks
      Adds each brick (with their X and Y coordinates) to the arrayList
     */
    }

   /* other methods, such as spinPiece() */
}

Do something like this:

public class Tetromino {
    private ArrayList<Tiles> tiles = new ArrayList<Tiles>();

     /* Tetrominoes basic methods that every Tetr does */
}

public class TetrominoShapeJ extends Tetromino {
     /* sets colour, space and spin-method in here */
}


texts:
I'm very new to programming in C and I attempted to make a program that converts temperatures to and from Fahrenheit and Celsius. I have been running the program and I have realized that not all conversions are correct. For example, if I use the boiling point of water (100C or 212F), I get an incorrect answer. I thought that I used the correct formulas. I was wondering if you wouldn't mind reviewing this quick program.

#include <stdio.h>
#include <stdlib.h>

int main(void) {

    float c;
    float f;
    int w;

    printf("Type 1 if you would like to convert to Farenheit\n");
    printf("Type 2 if you would like to convert to Celcius\n");

    scanf("%i", &w);

// Loop to make sure value is 1 or 2

    while(w != 1 && w !=2) {

        fprintf(stderr, "You didn't input a valid number. Please Try Again\n");
        scanf("%i", &w);
    }

// Celsius --> Fahrenheit
    if(w == 1){
        printf("Input the Celcius Temperature\n");
        scanf("%f", &c);
        printf("You entered %f\n", c);
        f = c * (9./5.) + 32.;
        printf("%f in Fareheit is %f\n", c, f);
     }

// Fahrenheit --> Celsius
    if(w == 2){
        printf("Input the Farenheit Temperature\n");
        scanf("%f", &f);
        printf("You entered %f\n",f);
        c = (f - 32.) * (5./9.);
        printf("%f in Celcius is %f\n", f, c);
    }

    return 0;
}


texts: Command-query segregation principle for an authenticator

texts:
The Authenticate method violates the command-query segregation principle, right? How can I adhere to the command-query segregation principle here?

public class Authenticator : IAuthenticator
{
    public bool Authenticated
    {
        get { return HttpContext.Current.User.Identity.IsAuthenticated; }
    }

    public bool Authenticate(string username, string password)
    {
        var authenticated = FormsAuthentication.Authenticate(username, password);
        if (authenticated)
            FormsAuthentication.SetAuthCookie(username, false);
        return authenticated;
    }

    public void Logout()
    {
       FormsAuthentication.SignOut();
    }
}


texts: Injecting a set of files in a Thymeleaf template while keeping the amount of tags at a minimum

texts:
I use a Thymeleaf template to inject a set of files (which contain precalculated HTML) into one big HTML. The files with their metadata are stored in a map called files, the files content is stored in another map called content. Both maps share the same key which is basically an id of the files.

The relevant section of the template has these lines:

        [(${content[ f.key ]})]

The result after this template was processed is:

Title of document with ID 1

    Content of file with ID 1

Title of document with ID 2

    Content of file with ID 2

This works fine but in order to place the th:each I had to introduce a superfluous div. Can I get rid of the div in the template and have a result like this:

Title of document with ID 1

Content of file with ID 1

Title of document with ID 2

Content of file with ID 2


texts:
So let's take this code which increments a Javascript text field value:

1

var counter = $(".counter")
counter.html( parseInt(counter.html()) + 1 )

It can be made shorter by using the Unary operator + which behaves like Number():

1

var counter = $(".counter")
counter.html( +counter.html() + 1 )

is there a shorter and better way to do this?

I tried combinations of the ones below, neither work:

1

$(".counter").html( +this.innerHTML + 1 )

and

1

$(".counter").html( +this.value + 1 )

and

1

$(".counter").html( +$this.html() + 1 )


texts: Script to print weather report from OpenWeatherMap API

texts:
This script prints the weather (fetching the information from a public API).

If anyone could review my code and answer my question about code structure and how should I code in the right way, I really appreciate that very much.

Questions:

I used many functions to do just one specific things, and return their value to be used in the next functions. Is this right?
In main I used composed way for calling functions, Is this right or there is a better way?

Note: You need to obtain your API key to try it.

import datetime
import json
import urllib.request

def time_converter(time):
    converted_time = datetime.datetime.fromtimestamp(
        int(time)
    ).strftime('%I:%M %p')
    return converted_time

def url_builder(city_id):
    user_api = ''  # Obtain yours form: http://openweathermap.org/
    unit = 'metric'  # For Fahrenheit use imperial, for Celsius use metric, and the default is Kelvin.
    api = 'http://api.openweathermap.org/data/2.5/weather?id='     # Search for your city ID here: http://bulk.openweathermap.org/sample/city.list.json.gz

    full_api_url = api + str(city_id) + '&mode=json&units=' + unit + '&APPID=' + user_api
    return full_api_url

def data_fetch(full_api_url):
    url = urllib.request.urlopen(full_api_url)
    output = url.read().decode('utf-8')
    raw_api_dict = json.loads(output)
    url.close()
    return raw_api_dict

def data_organizer(raw_api_dict):
    data = dict(
        city=raw_api_dict.get('name'),
        country=raw_api_dict.get('sys').get('country'),
        temp=raw_api_dict.get('main').get('temp'),
        temp_max=raw_api_dict.get('main').get('temp_max'),
        temp_min=raw_api_dict.get('main').get('temp_min'),
        humidity=raw_api_dict.get('main').get('humidity'),
        pressure=raw_api_dict.get('main').get('pressure'),
        sky=raw_api_dict['weather'][0]['main'],
        sunrise=time_converter(raw_api_dict.get('sys').get('sunrise')),
        sunset=time_converter(raw_api_dict.get('sys').get('sunset')),
        wind=raw_api_dict.get('wind').get('speed'),
        wind_deg=raw_api_dict.get('deg'),
        dt=time_converter(raw_api_dict.get('dt')),
        cloudiness=raw_api_dict.get('clouds').get('all')
    )
    return data

def data_output(data):
    m_symbol = '\xb0' + 'C'
    print('---------------------------------------')
    print('Current weather in: {}, {}:'.format(data['city'], data['country']))
    print(data['temp'], m_symbol, data['sky'])
    print('Max: {}, Min: {}'.format(data['temp_max'], data['temp_min']))
    print('')
    print('Wind Speed: {}, Degree: {}'.format(data['wind'], data['wind_deg']))
    print('Humidity: {}'.format(data['humidity']))
    print('Cloud: {}'.format(data['cloudiness']))
    print('Pressure: {}'.format(data['pressure']))
    print('Sunrise at: {}'.format(data['sunrise']))
    print('Sunset at: {}'.format(data['sunset']))
    print('')
    print('Last update from the server: {}'.format(data['dt']))
    print('---------------------------------------')

if __name__ == '__main__':
    try:
        data_output(data_organizer(data_fetch(url_builder(2172797))))
    except IOError:
        print('no internet')

Output:

---------------------------------------
Current weather in: Cairns, AU:
14.81 °C Clear
Max: 17, Min: 10.56

Wind Speed: 1.91, Degree: None
Humidity: 100
Cloud: 0
Pressure: 1015
Sunrise at: 11:41 PM
Sunset at: 10:50 AM

Last update from the server: 11:35 PM
---------------------------------------


texts: Format the output of Color.ToString() to RGB values

texts:
The method that I wrote below functions properly; however, I believe that the code I wrote is not clean nor "good".

I know the basics of regex but I do not know more advanced techniques as I am still an amateur at programming.

static string SimpleColorOutput(Color color)
{
    //If input = Color[A=255, R=8, G=14, B=21]

    string colorText = color.ToString();

    Match R = Regex.Match(colorText, @"R=(\d+)[,\]]");
    Match G = Regex.Match(colorText, @"G=(\d+)[,\]]");
    Match B = Regex.Match(colorText, @"B=(\d+)[,\]]");

    return $"R = {R.Groups[1].Value}, G = {G.Groups[1].Value}, B = {B.Groups[1].Value}";

    //The method returns "R = 7, G = 13, B = 20"
}

Also, is it better to just pass in the Color object


texts:
Assume the following definition:

public class DataPoint {
    public DateTime Date { get; private set; }
    public double Value { get; private set; }
    public DataPoint(DateTime date, double value) { Date = date; Value = value; }
}

If var points = ... //a date ordered list of DataPoints

I want to convert points into a list or array that represents the steps between each subsequent value. E.g. [3, 5, 6, 10.5] would go to [3, 2, 1, 4.5] with dates.

Here's what I have:

var steps = (new[] {points.First()})
              .Concat(points
                        .Skip(1)
                        .Zip(points,
                            (curr, prev) => new DataPoint(curr.Date, curr.Value - prev.Value)))

I think my ruby background might have gotten the best of me as that doesn't seem very readable. Any thoughts on how to make things more approachable?


texts:
This is the draft contents of a function intended to be run after a system crash in order to quickly review all of the recent vim swap files. They will be loaded up into and displayed in a vim instance, and then presumably if desired they will be saved using vim commands into actual files. Following this, rm will be run to offer user to delete the swap files. In theory, unless user gets distracted by something in between quitting the vim instance and responding to the rm -i prompt, there shouldn't be cases in which the swap file gets preserved, but better to be safe with these things I guess, and add additional 2 keystrokes to the workflow per file.

vim=gvim
n=5
d=.
days_back=3
echo Searching
find "$1" -type f \( -name '.*.s??' -o -name '.s??' \) -exec ls -lta {} + | head -n "$2"
find "$d" -type f \( -name '.*.s??' -o -name '.s??' \) -mtime "$days_back" -printf "%AY%Am%Ad%AH%AM%AS %p\0\n" |
    sort -n     |
    head "$n"   |
    sed -e 's/\d+ //' | sed -e 's/\n//g' | while read -r -d '' f; do
        $vim -r "$f" && rm -iv "$f" ||
                echo ERROR: vim recovery command returned failure status.

    done

2nd iteration:

function swap_sweep () {
    # Usage: swap_sweep [ DAYS_BACK ]
    #   Sweeps the current working directory for swap files, sorted by the most recent order,
    #   going DAYS_BACK days back if it is provided, or 3 days back if it is not.

    # [[ -d $1 ]]   && ( d="$1" && n="$2" ) || n="$1"
    # [[ -z $d ]] && d=.

    vim=gvim
    wd=.
    [[ -n $1 ]] && days_back=$1 || days_back=3
    # I wonder if these awk commands will accomodate filenames that contain whitespace...
    # I'm guessing not, and wonder how that could be done?
    find "$wd"  -type f \
                -mtime "$days_back" \
                    \( -name '.*.s??' -o -name '.s??' \) \
                -exec ls -ltago {} +             \
        | awk '{ print $4, $5, $6, $7, }'        \
                                 \
        | tee | awk '{ print $4 }' \
        | while read -r f; do
            $vim -r "$f" && rm -iv "$f" ||
                    echo ERROR: vim recovery command returned failure status.
        done
}

alias sws=swap_sweep

3rd iteration:

function swap_sweep () {
    days_back=3
    vim=gvim
    n=5
    wd=.
    echo Searching
    find "$wd" -type f \( -name '.*.s??' -o -name '.s??' \) -mtime "$days_back" -exec ls -ltago {} + |
        awk '{ print $4, $5, $6, $7 }'
    find "$wd" -type f \( -name '.*.s??' -o -name '.s??' \) -mtime "$days_back" -print0 | while read -r -d '' f; do
            $vim -r "$f" && rm -iv "$f" ||
                            echo ERROR: vim recovery command returned failure status.
    done
##  # Usage: swap_sweep [ DAYS_BACK ]
##  #   Sweeps the current working directory for swap files, sorted by the most recent order,
##  #   going DAYS_BACK days back if it is provided, or 3 days back if it is not.
##
##  # [[ -d $1 ]]   && ( d="$1" && n="$2" ) || n="$1"
##  # [[ -z $d ]] && d=.
##
##  vim=gvim
##  wd=.
##  [[ -n $1 ]] && days_back=$1 || days_back=3
##  # I wonder if these awk commands will accomodate filenames that contain whitespace...
##  # I'm guessing not, and wonder how that could be done?
##  find "$wd"   -type f \
##              -mtime "$days_back" \
##                  \( -name '.*.s??' -o -name '.s??' \) \
##              -exec ls -ltago {} +             \
##      | awk '{ print $4, $5, $6, $7 }'         \
##                               \
##      | tee | awk '{ print $4 }' \
##      | while read -r f; do
##          $vim -r "$f" &&
##              echo -n "$(ls -lhgo "$f" | awk '{ print $7, "\t", $4, $5, $6 }')    ==> " &&
##              rm -iv "$f" ||
##          echo ERROR: vim recovery command returned failure status.
##      done
}

```


texts: Adding elements of 2 linked list in reverse order

texts:
I solved a problem with JavaScript which has the following requirements:

Two non-empty linked lists representing two non-negative integers.
Digits stored in reverse order
Each node contains a single digit
Add the two numbers and return it as a linked list

Sample I/O:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807

My code:

 /**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
  let l1Str = "";
  let l2Str = "";
  while (l1 !== null) {
    l1Str += l1.val.toString();
    l1 = l1.next;
  }

  while (l2 !== null) {
    l2Str += l2.val.toString();
    l2 = l2.next;
  }

  let sum = (BigInt(l1Str.split("").reverse().join("")) + BigInt(l2Str.split("").reverse().join(""))).toString();

  let resultNodeList = new ListNode(sum[sum.length - 1]);
  let resultHead = resultNodeList;
  for (let i = sum.length - 2;i >= 0;i--) {
    resultNodeList.next = new ListNode(sum[i]);
    resultNodeList = resultNodeList.next;
  }

  return resultHead;

};

Note: I had to use BigInt cause parseInt won't work on big integers as expected.

Although it passed all test cases, what are some ways to improve this code in terms of both time and space complexity?


texts:
Can anyone offer any criticism on the following at a simple FizzBuzz in terms of Ruby idioms or otherwise?

class FizzBuzz

  def initialize(fizz = 'Fizz', buzz = 'Buzz')
    @fizz = fizz
    @buzz = buzz
  end

  def is_number_divisible_by?(number, divisor)
    number % divisor == 0
  end

  def get_text(number)
    fizz_buzz_text = ''
    if is_number_divisible_by?(number, 3)
      fizz_buzz_text += @fizz
    end
    if is_number_divisible_by?(number, 5)
      fizz_buzz_text += @buzz
    end
    return fizz_buzz_text
  end

end

fb = FizzBuzz.new
(1...101).each do |i|
  fb_text = fb.get_text(i)
  puts fb_text.empty? ? i : fb_text
end


texts: Checking if input is a string or an integer

texts:
I'm teaching myself C++ by reading Stroupstrup's Programming Principles and Practice Using C++, and I'm working on an exercise in chapter 4. The exercise asks to convert input as a digit to the corresponding spelled-out value e.g. input of 1 gives the output "one".

#include "std_lib_facilities.h"

using namespace std;

//Workaround for compiler issue.
int stoi( const std::string& str, std::size_t* pos = 0, int base = 10 )
    {
        const char* begin = str.c_str() ;
        char* end = nullptr ;
        long value = std::strtol( begin, &end, base ) ;

        if( errno == ERANGE || value > std::numeric_limits<int>::max() )
            throw std::out_of_range( "stoi: out ofrange" ) ;

        if( end == str.c_str() )
            throw std::invalid_argument( "stoi: invalid argument" ) ;

        if(pos) *pos = end - begin ;

        return value ;
    }

int main()
{
    struct Numbers
    {
        string spelled;
        int digit;
    };
    const Numbers nums[]
    {
        {"zero", 0},
        {"one", 1},
        {"two", 2},
        {"three", 3},
        {"four", 4},
        {"five", 5},
        {"six", 6},
        {"seven", 7},
        {"eight", 8},
        {"nine", 9},
        {"ten", 10}
    };

    string response = " ";

    cout << "Type a number either spelled out or as a digit.\n";

    cin >> response;
    if(response.size() == 1)
    {
        cout << nums[stoi(response)].spelled;
    }
    else if(response.size() > 1)
    {
        for(int i=0; i<=10; ++i)
        {
            if(response == nums[i].spelled)
            {
                cout << nums[i].digit << endl;
                break;
            }
            else;
        }
    }
}

Is there a better way to check the type of input the user gives other than checking the response size? Would it have been easier/more efficient if I had used a vector? In my for loop, does that break in the if statement break the loop?


texts: Extract a character at particular place in a string

texts:
I have a function:

Private Function getbyte(s As String, ByVal place As Integer) As String
If place < Len(s) Then
place = place + 1
getbyte = Mid(s, place, 1)
Else
getbyte = ""
End If
End Function

For extracting a character at a particular place in a string, how can I shorten this or any alternate for the same purpose?


texts: Simple object oriented design for an Allergy class

texts:
Build a system for entering and displaying the allergies that patients may have.
  The allergy will have its own set of symptoms reactions. The allergy will also have a spectrum of severity which the clinician should be aware of, and allergies can be reported by the patient or by next of kin.

Please review my code and tell me how I can improve my object-oriented design.

class Allergy

    attr_accessor :name, :reporter, :time_reported
    attr_reader :symptoms

    def initialize(name, reporter, time_reported=Time.now)
        @name = name
        @reporter = reporter
        @symptoms = []
        @time_reported = time_reported
    end

    def add_symptoms(symptom, severity)
        symptom = Symptom.new(symptom, severity)
        @symptoms.push(symptom)
    end

end

class Symptom
    attr_accessor :symptom, :severity

    def initialize(symptom, severity)
        @symptom = symptom
        @severity = severity
    end

end


texts: Protecting webpage text from being selected

texts:
I've got a text I don't want to be copied by users.
To avoid that, I'm using this code:
index.php

<?php
session_start();
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < 100; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
$_SESSION['token'] = $randomString;
?>
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Test</title>

Please wait...

page.php

<?php
session_start();
if(!empty($_SESSION['token']) AND $_GET['token']==$_SESSION['token']){echo '

Text...';
unset($_SESSION['token']);
}
else{echo 'Error.';
}
?>

Is this method reliable?


texts: Get a movie directory, rename it and save imdb info as a webpage

texts:
I have my movie folders formatted:

~: no sub included
{}: already watched
nothing: sub included, ready to watch

the program asks for the movie directory; extracts the name and searches IMDb for the name; renames the given directory to the first IMDb search result.

finally saves what you'd see when the first result is clicked as a .html file in the given directory.

import urllib
import requests
import os
import re
from bs4 import BeautifulSoup

# write response page in tmp.html
def movNameSearch(path, movie):
    print('Fetching...\n')
    url = "https://www.imdb.com/find?ref_=nv_sr_fn&q=" + movie + "&s=tt"
    response = requests.get(url) #get response
    resTxt = response.text
    soup = BeautifulSoup(resTxt, 'html.parser') #parsed response
    findList = soup.find_all('td', class_ = 'result_text') #all founded movies
    someList = []
    for i in range(10):
        theRes = findList[i].contents[1].contents[0] + findList[i].contents[2]
        someList.append(theRes)

    for j in range(len(someList)):
        print(str(j+1) + '. ' + someList[j])

    selection = int(input('\nWhich is the desired result? '))
    rec = findList[selection-1].contents #first found result - recommended
    recText = rec[1].contents[0] #movie name
    fullName = recText + rec[2] #movie year
    suggestion = 'Confirm ' + fullName + '? (y/n) '
    accept = input(suggestion)
    if accept == 'y':
        print('Renaming the folder...')
        #rename folder
        pathArray = path.split(sep='/')
        if pathArray[-1] == '': # / at the end
            pathArray.pop()
            pathArray.pop()
        else: #no / at the end
            pathArray.pop()
        pathArray.append(fullName)
        src = path
        dst = '/'.join(pathArray)
        os.rename(src, dst)
        print('Renamed to ' + fullName)

        #generate info into info.txt
        imdbUrl = 'https://www.imdb.com'
        toAdd = list(rec[1].parent.contents[1].attrs.values())[0]
        imdbUrl = imdbUrl + toAdd
        result = [imdbUrl, dst]
        return result
    else:
        print('K bye')

def getInfo(url, path):
    print('Fetching extra info...')
    response = requests.get(url)
    resTxt = response.text
    soup = BeautifulSoup(resTxt, 'html.parser')
    print('Generating extra info...')
    f = open(path + '/info.html', 'w+')
    f.write(resTxt)
    print('Complete.')
    return True

#/home/name/some/~{}folder
# open directory =>
# get path
mainPath = str(input("Enter movie directory: "))
movName = re.split("/", mainPath)
if movName[-1] == '':
    movName = movName[-2]
else:
    movName = movName[-1]

# remove extra chars
movName = re.sub("[~{}]", "", movName).capitalize()

# check
accept = input("Confirm " + movName + " ? (y/n) ")
if accept == "y":
    result = movNameSearch(mainPath, movName)
    if len(result) == 2:
        stat = getInfo(result[0], result[1])
        if stat == True:
            print('Success! Quitting now.')
    else:
        print('K Bye')

else:
    print("K bye")


texts: The eternal dilemma: bar.foo() or foo(bar)?

texts:
I was using foo(bar) as it's adopted for functional programming.

console.log(
    join(
        map(function(row){ return row.join(" "); },
            tablify(
                map(function(text){return align(text},
                    view),
                20))),
    "\n");

Now, with dot operator:

view.map(function(text){return align(text)})
    .tablify(20)
    .map(function(row){return row.join(" ");})
    .join("\n")
    .log();

I guess everyone will agree this reads too much better, and the only cost is that you have to modify the native types prototype. So, which?


texts: Removing duplicates from an unsorted linked list

texts:
Does the code below look correct and efficient for removing duplicates from an unsorted linked list without using extra memory?

An object of type Node denotes a LL node.

void removeDuplicates()
{
  Node current = head;
  while(current!=null)
  {
    Node prev = current;
    Node next = current.next;
    while(next!=null)
    {
      if(current.equals(next))
      {
         prev.next = next.next;
      }
      else
      {
         prev = next;
      }
      next = next.next;
    }
      current = current.next;
   }
}


texts:
I have found myself referencing controls on a form (think Windows forms but more proprietary) by hard-typing their names in over and over again. Often I'll have a number of similar controls which could be named coolControl1department, coolControl2department, coolControl1jobTitle, coolControl2jobTitle, etc. This becomes tedious and a nightmare to maintain. Renaming the controls is definitely an option but I would still need some way of generating their names to assign values and whatnot.

To make this less reliant on me typing in the names I've created a dictionary method to concatenate the various parts of the control names, including unique reference numbers, and then call the final values elsewhere.

While it's more centralised than it was previously, there is still room for improvement and I'd appreciate any suggestions to streamline this.

Note that I'm only able to use C# version 4.0 in this application. Code below.

    public void DoStuffWithControls()
    {
        Dictionary<string, string> myControls1 = GeneratedControlNames(1);
        Dictionary<string, string> myControls2 = GeneratedControlNames(2);
        string genericControl1;
        string genericControl2;
        string departmentControl1;
        string departmentControl2;
        myControls1.TryGetValue("generic", out genericControl1);
        myControls1.TryGetValue("department", out departmentControl1);
        myControls2.TryGetValue("generic", out genericControl2);
        myControls2.TryGetValue("department", out departmentControl2);
        EnquiryForm.GetEnquiryControl(genericControl1, EnquiryControlMissing.Exception).Value = "some value";
        EnquiryForm.GetEnquiryControl(departmentControl1, EnquiryControlMissing.Exception).Value = "some value";
        EnquiryForm.GetEnquiryControl(genericControl1, EnquiryControlMissing.Exception).AnotherProperty = "some other value";
        EnquiryForm.GetEnquiryControl(genericControl2, EnquiryControlMissing.Exception).Value = "some value";
        EnquiryForm.GetEnquiryControl(genericControl2, EnquiryControlMissing.Exception).AnotherProperty = "some other value";
        EnquiryForm.GetEnquiryControl(departmentControl2, EnquiryControlMissing.Exception).Value = "some value";
    }

    private static Dictionary<string, string> GeneratedControlNames(int refNumber)
    {
        var genericPrefix = "coolControl";
        var departmentControlSuffix = "Department";
        var jobTitleControlSuffix = "Title";
        var directDialControlSuffix = "DDI";
        var emailDialControlSuffix = "Email";

        var dict = new Dictionary<string, string>();
        dict.Add("generic", string.Concat(genericPrefix, refNumber));
        dict.Add("department", string.Concat(genericPrefix, refNumber, departmentControlSuffix));
        dict.Add("jobTitle", string.Concat(genericPrefix, refNumber, jobTitleControlSuffix));
        dict.Add("directDial", string.Concat(genericPrefix, refNumber, directDialControlSuffix));
        dict.Add("email", string.Concat(genericPrefix, refNumber, emailDialControlSuffix));
        return dict;
    }


texts: Print all interleavings of two given strings

texts:
Given two strings str1 and str2, write a function that prints all
  interleavings of the given two strings. You may assume that all
  characters in both strings are different

  Example:

Input: str1 = "AB",  str2 = "CD"
Output:
    ABCD
    ACBD
    ACDB
    CABD
    CADB
    CDAB

Input: str1 = "AB",  str2 = "C"
Output:
    ABC
    ACB
    CAB

  The idea comes from Ray Toal:

  The base case is when one of the two strings are empty:

interleave(s1, "") = {s1}

interleave("", s2) = {s2}

  Notice the order of the arguments doesn't really matter, because

interleave("ab", "12") = {"ab12", "a1b2", "1ab2", "a12b", "1a2b", "12ab"} = interleave("12", "ab")

  So since the order doesn't matter we'll look at recursing on the length of the first string.

  Okay so let's see how one case leads to the next. I'll just use a
  concrete example, and you can generalize this to real code.

interleave("", "abc") = {"abc"} interleave("1", "abc") = {"1abc",
"a1bc", "ab1c", "abc1"} interleave("12", "abc") = {"12abc", "1a2bc",
"1ab2c", "1abc2", "a12bc", "a1b2c", "a1bc2", "ab12c", "ab1c2" "abc12"}

  So everytime we added a character to the first string, we formed the
  new result set by adding the new character to all possible positions
  in the old result set. Let's look at exactly how we formed the third
  result above from the second. How did each element in the second
  result turn into elements in the third result when we added the "2"?

"1abc" => "12abc", "1a2bc", "1ab2c", "1abc2" "a1bc" => "a12bc",
"a1b2c", "a1bc2" "ab1c" => "ab12c", "ab1c2" "abc1" => "abc2"

  Now look at things this way:

"1abc" => {1 w | w = interleave("2", "abc")} "a1bc" => {a1 w | w =
interleave("2", "bc")} "ab1c" => {ab1 w | w = interleave("2", "c")}
"abc1" => {abc1 w | w = interleave("2", "")}

The following is my code building on top of the above idea.  Can anyone help me verify it?

void interleaving(const string& s2, string result, int start, int depth)
{
    if(depth == s2.size())
        cout << result << endl;
    else
    {
        for(int i = start; i <= result.size(); ++i)
        {
            result.insert(i, 1, s2[depth]);
            interleaving(s2, result, i+1, depth+1);
            result.erase(i, 1);
        }
    }
}

int main()
{
    string s1("");
    string s2("12");
    string result(s1);
   interleaving(s2, result, 0, 0);
    system("pause");
    return 0;
}

There is another much more beautiful solution for this problem comes from an unknown friend akash01:

void printIlsRecur (char *str1, char *str2, char *iStr, int m, int n, int i)
{
    // Base case: If all characters of str1 and str2 have been included in
    // output string, then print the output string
    if ( m==0 && n ==0 )
    {
        printf("%s\n", iStr) ;
    }

    // If some characters of str1 are left to be included, then include the
    // first character from the remaining characters and recur for rest
    if ( m != 0 )
    {
        iStr[i] = str1[0];
        printIlsRecur (str1 + 1, str2, iStr, m-1, n, i+1);
    }

    // If some characters of str2 are left to be included, then include the
    // first character from the remaining characters and recur for rest
    if ( n != 0 )
    {
        iStr[i] = str2[0];
        printIlsRecur (str1, str2+1, iStr, m, n-1, i+1);
    }
}