texts: Finding the maximum sum of any 2 elements in an array of integers

texts:
this no-brainer came up to me in a technical interview. I played it safe and wrote this.

 public class Main {

  public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    System.out.println("enter size of the array: ");

    if (!in.hasNextInt()) {
      System.out.println("put an integer! ");
    }
    int size = in.nextInt();

    System.out.println("enter numbers for array");

    int[] array = new int[size];

    for (int i = 0; i < array.length; i++) {
      array[i] = in.nextInt();
    }

    maxSum(array);

    System.out.println(maxSum(array));
  }

  private static int maxSum(int[] array) {

    int max = array[0];

    for (int i = 0; i < array.length; i++) {
      for (int j = i + 1; j < array.length; j++) {

        int currentMax = array[i] + array[j];

        if (currentMax > max) {
          max = currentMax;
        }
      }
    }

    return max;
  }
}

obviously O(n^2) is not the best approach but I just wanted to finish the question without spending to much time, what do you think?


texts: Selecting function overload based on a type match with return value of passed callable

texts:
On an std::list<A> or std::vector<A> or other collection container, the functor map (fmap) operation takes a function/callable of type B(A) and applies it elementwise to a list of As to get a list of Bs:

// Pseudo-code
container<B> fmap( B(A) f, container<A> xs)
{
  // Apply f elementwise to xs, and collect the results and...
  return result;
}

If A and B are the same, then fmap can take the list by copy, and mutate its copy and return it. Otherwise, I want to take the input container by const reference, and create a new container for the results. The following code works (using clang++4.0 -std=c++1z) but it's just so unspeakably ugly for such a simple thing.

#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <numeric>
#include <type_traits>
#include <vector>

// clang-format off
template <template <typename, typename> class Container, typename A, typename F,
  // Enables this overload if the container's element type matches the output
  //   type of the callable:
  typename = std::enable_if_t<std::is_same< A,
    decltype(std::invoke(std::declval<F>(), std::declval<A>()))>::value>>
auto fmap(F f, Container<A, std::allocator<A>> xs) {
  std::cout << "I/O type SYMMETRY DETECTED!!\n";
  std::transform(std::begin(xs), std::end(xs), std::begin(xs), f);
  return xs;
}
// clang-format on

// clang-format off
template <template <typename, typename> class Container, typename A, typename F,
typename = std::enable_if_t< ! std::is_same< A,
  decltype(std::invoke(std::declval<F>(), std::declval<A>()))>::value>>
auto fmap(F f, const Container<A, std::allocator<A>>& xs) {
  std::cout << "I/O type MISMATCH DETECTED!!\n";
  using B = decltype(f(std::declval<A>()));
  using ContainerOfB = Container<B, std::allocator<B>>;

  ContainerOfB result;

  if constexpr(std::is_same<ContainerOfB, std::vector<B>>::value) {
    result.reserve(xs.size());
  }
  std::transform(std::begin(xs), std::end(xs), std::back_inserter(result), f);

  return result;
}

template <typename T>
void printrange(const T r) {
  std::copy(std::cbegin(r), std::cend(r),
            std::ostream_iterator<decltype(*std::begin(r))>(std::cout, ", "));
}

int main() {
  std::vector<int> v(20);
  std::iota(v.begin(), v.end(), 0);

  // clang-format off
  printrange(
      fmap([](int i) { return '\'' + std::to_string(i) + '\''; },
      fmap([](int x) { return x * x; },
      fmap([](int x) { return x + 1; }, v) ))
  );
  // clang-format on

  return 0;
}

Forgive me, I'm new to to template metaprogramming, and I'm aware that I'm not doing anything difficult. In fact, everything I'm using is in <type_traits>, so I'm not really doing any metafunction programming, I'm just using metafunctions! But the code I just wrote is so heinously ugly that I'm sure it can be polished and prettied. I seek the greater wisdom of the community to help me clean up this mess.


texts: Counting length-2 substrings that are common to two strings at the same offset

texts:
I am working through the CodingBat exercises for Java. I just completed this one, an exercise that requests the comparison of substrings of two strings:

  Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings.

stringMatch("xxcaazz", "xxbaaz") → 3
stringMatch("abc", "abc") → 2
stringMatch("abc", "axc") → 0

Here is my method (which does work):

public int stringMatch(String a, String b) {
    int count = 0;

    String sub2 = "";

    String arrayA[] = new String[a.length()];
    String arrayB[] = new String[b.length()];

    for (int i = 0; i < a.length()-1; i++) {
        sub2 = a.substring(i, i+2);
        arrayA[i] = sub2;
    }

    for (int i = 0; i < b.length()-1; i++) {
        sub2 = b.substring(i, i+2);
        arrayB[i] = sub2;
    }

    for (int j = 0; j < arrayA.length-1; j++) {

        if (j >= b.length())
            break;

        if (arrayA[j].equals(arrayB[j]))
            count++;
    }

    return count;
}

And here is the answer on the site:

public int stringMatch(String a, String b) {

  int len = Math.min(a.length(), b.length());
  int count = 0;

  for (int i=0; i<len-1; i++) {
    String aSub = a.substring(i, i+2);
    String bSub = b.substring(i, i+2);
    if (aSub.equals(bSub)) {  // Use .equals() with strings
      count++;
    }
  }

  return count;
}

I feel that my code is longer and messy and drawn out compared to other people's.  As a beginner programmer, how should I improve it?


texts:
I am writing a wrapper for dynamic behavior in C#. If I use GetMethod(), then an exception is thrown when there is more than one method (overloads).  I figure it will become apparent at runtime that if there is an argument mismatch anyway.  Is this a good way to solve the problem?

public class StaticMembersDynamicWrapper : DynamicObject
{
  private Type _type;

  public StaticMembersDynamicWrapper(Type type) { _type = type; }

  // Handle static methods
  public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
  {
     var methods = _type
        .GetMethods(BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public)
        .Where(methodInfo => methodInfo.Name == binder.Name);

     var method = methods.FirstOrDefault();
     if (method != null)
     {
        result = method.Invoke(null, args);
        return true;
     }

     result = null;
     return false;
  }
}


texts:
I have two python scripts (or one bash script + one python script) which are working independently from another, one script puts data into a folder, the other one reads from it.
Since I don't want to accidentally read from the folder at the same time it's updated, I created this simple folder lock using a dummy file.
In the bash script a similar thing is done, by checking whether that lock.file exists, and if not create it, put the current PID into it, and after it's done delete it.
import os
import sys
import time
import logging

LOGGER = logging.getLogger()

class SimpleFolderLock():
    def __init__(self, folder_path, time_out=5):
        self._folder_to_lock = folder_path
        self._lock_file_path = os.path.join(self._folder_to_lock, "folder.lock")
        self._lock_time_out = time_out

    def __enter__(self):
        start_time = time.time()
        while os.path.exists(self._lock_file_path):
            LOGGER.debug(f"Waiting for {self._lock_file_path} to clear")
            time.sleep(5)
            if (time.time() - start_time) > self._lock_time_out:
                LOGGER.error(
                    f"Time-out for waiting for {self._lock_file_path} to clear")
                raise TimeoutError(f"Can't lock {self._folder_to_lock} after {self._lock_time_out} seconds")

        LOGGER.debug(f"Locking with {self._lock_file_path}")
        with open(self._lock_file_path, "w") as fn:
            fn.write(str(os.getpid()))

        return self._lock_file_path

    def __exit__(self, type, value, traceback):
        try:
            LOGGER.debug(f"Clearing {self._lock_file_path}")
            os.remove(self._lock_file_path)
        except FileNotFoundError:
            LOGGER.error(f"File {self._lock_file_path} already got deleted")

And for a simple test:
# Just some dummy logging configuration
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
test_folder = "/tmp/test_dir/"
os.makedirs(test_folder, exist_ok=True)
with SimpleFolderLock(test_folder) as lock:
    lock_path = lock
    LOGGER.info(f"Locked with {lock_path}")
    assert os.path.exists(lock_path)
    fiddle_around_in_folder(test_folder)

assert not os.path.exists(lock_path)


texts:
I am looking for some comments on an implementation of a singly-linked list in Python. What could I do to make it more reliable and readable?

class LinkedList(object):
    class Node(object):
        """
        Inner class of LinkedList. Contains a blueprint for a node of the LinkedList
        """
        def __init__(self, v, n=None):
            """
            Initializes a List node with payload v and link n
            """
            self.value=v
            self.next=n

    def __init__(self):
        """
        Initializes a LinkedList and sets list head to None
        """
        self.head=None

    def insert(self, v):
        """
        Adds an item with payload v to beginning of the list
        in O(1) time
        """
        Node = self.Node(v, self.head)
        self.head = Node

    def size(self):
        """
        Returns the current size of the list. O(n), linear time
        """
        current = self.head
        count = 0
        while current:
            count += 1
            current = current.next
        return count

    def search(self, v):
        """
        Searches the list for a node with payload v. Returns the node object or None if not found. Time complexity is O(n) in worst case.
        """
        current = self.head
        found = False
        while current and not found:
            if current.value == v:
                found = True
            else:
                current = current.next
        if not current:
            return None
        return current

    def delete(self, v):
        """
        Searches the list for a node with payload v. Returns the node object or None if not found. Time complexity is O(n) in worst case.
        """
        current = self.head
        previous = None
        found = False
        while current and not found:
            if current.value == v:
                found = True
            else:
                previous = current
                current = current.next
        # nothing found, return None
        if not current:
            return None
        # the case where first item is being deleted
        if not previous:
            self.head = current.next
        # item from inside of the list is being deleted
        else:
            previous.next = current.next

        return current

    def __str__(self):
        """
        Prints the current list in the form of a Python list
        """
        current = self.head
        toPrint = []
        while current != None:
            toPrint.append(current.value)
            current = current.next
        return str(toPrint)


texts: Executing a program with a temporary directory and measuring the running time

texts:
I need a code review for best practices and code correctness of the following piece of code. run executes a program and validates in output. If the output is valid status can be found in VALID_SOLUTIONS.

elapsed = None
tmpdir = tempfile.mkdtemp(prefix='structure-%s-' % os.path.basename(instance))
try:
  for r in range(options.repeat):
    run_returncode, run_status, run_elapsed = run(
        r, path, program, tmpdir, options.timeout, options.satisfiable)
    if run_status not in VALID_SOLUTIONS:
      returncode, status, elapsed = run_returncode, run_status, None
      break

    if r == 0:
      # Set the expected results
      returncode, status = run_returncode, run_status
      elapsed = [run_elapsed]
    else:
      if returncode != run_returncode or status != run_status:
        # Results don't match
        returncode, status, elapsed = None, 'inconsistent_results', None
        break
      else:
        # Extra set
        elapsed.append(run_elapsed)
except Exception as e:
  # Unexpected error in script itself
  print(e, file=sys.stderr)
  #traceback.print_exc()
  status = 'error'
except KeyboardInterrupt as e:
  print('interrupted', file=sys.stderr)
  returncode, status, elapsed = None, 'interrupted', None
finally:
  if status in VALID_SOLUTIONS:
    avg = sum(elapsed) / len(elapsed)
    std = (sum((e - avg)**2 for e in elapsed) / len(elapsed)) ** 0.5
    ci = 1.96 * std / (len(elapsed) ** 0.5)
    print(instance, returncode, status, avg, ci)
  else:
    print(instance, returncode, status, None, None)

  sys.stdout.flush()
  exit(int(status not in ['interrupted'] + VALID_SOLUTIONS))


texts:
I have a website that, based on a user's comments, filters comments by "most liked first, most disliked first" etc...

I have a custom table for comments scoring system and system working with +1 and -1's.

A few days ago I wanted to filter comments by most liked and most disliked as I said and wrote this code:

In my functions.php

function bestanswers($a){

    global $wpdb;

    $results = $wpdb->get_results( 'SELECT * FROM wp_comments LEFT JOIN wp_custom_scoring ON wp_custom_scoring.entryID = wp_comments.comment_ID WHERE class="point" and comment_post_ID='.intval($a).' AND type="plus" GROUP BY entryID ORDER BY COUNT(entryID) DESC');

    if(empty($results)){
        echo 'Its Empty!';
        return false;
    }else{
        return $results;
    }
}

And in my functions.php again:

function score($a,$b){

    if($b == "minus"){
    global $wpdb;
    $results = $wpdb->get_results( 'SELECT count(id) as total,type,class,entryID FROM wp_custom_scoring WHERE type="minus"  and class="point" and entryID='.intval($a));

        if($results[0]->total!= 0){
            return "-".$results[0]->total;
        }else{
            return 0;
        }

    }elseif($b == "plus"){
    global $wpdb;
    $results = $wpdb->get_results( 'SELECT count(id) as total,type,class,entryID FROM wp_custom_scoring WHERE type="plus"  and class="point" and entryID ='.intval($a));

        if($results[0]->total != 0){
            return "+".$results[0]->total;
        }else{
            return 0;
        }

    }else{
    global $wpdb;
    $results = $wpdb->get_results( 'SELECT count(id) as total,class,entryID FROM wp_custom_scoring WHERE  class="fav" and entryID='.intval($a));

    return $results[0]->total;
    }

}

And in comments.php:

if(isset($_GET['filter']) and sanitize_text_field(esc_attr($_GET['filter'])) == 'bestanswers'){

foreach (bestanswers($postID) as $bests) {
if ( score($bests->comment_ID,"plus") + score($bests->comment_ID,"minus") > 0 ){
echo $bests->comment_ID;
comment_text($bests->comment_ID);
///...etc with my custom theme template
}

It's working and I'm able to get everything as I wanted but it's looking ugly to me. Is there are any better way to do this? Or any improvement on my code?


texts: Questions regarding the use of Requests Futures for accessing REST URLs

texts:
This is a much simplified version of the real code focusing just on the handling of Futures from Requests Futures.

I have a few questions:

I had to implement my own version of as_completed because the data handlers may add more Futures to _pending. Is this a decent way to handle the problem, or is there another approach?
Is stop sufficient to handle KeyboardInterrupt in all cases? It has worked well in my limited testing. I found it hard to find a solution via Google.
Is my rate limiting solution OK or is there a better approach? It is not about the number of concurrent connections but about the number of connections per second.

import argparse
from concurrent.futures import ThreadPoolExecutor
import requests
from requests_futures.sessions import FuturesSession
import time

def background_callback(sess, resp):
    # parse the json storing the result on the response object
    if resp.status_code == requests.codes.ok:
        resp.data = resp.json()
    else:
        resp.data = None

class JSONRetriever(object):
    def __init__(self):
        self._executor = ThreadPoolExecutor(max_workers=10)
        self._session = FuturesSession(executor=self._executor)
        self._pending = {}

    def fetch(self, url):
        future = self._session.get(url,
                                   background_callback=background_callback)
        self._pending[future] = url

    def drain(self):
        # Look for completed requests by hand because in the real code
        # the responses my trigger further URLs to be retrieved so
        # self._pending is modified. New requests being added really
        # confused as_completed().
        for future in [f for f in self._pending if f.done()]:
            url = self._pending[future]
            del self._pending[future]

            response = future.result()
            response.raise_for_status()
            if response.status_code == requests.codes.ok:
                print response.data
                # real code would handle data possibly adding more requests
            else:
                # the real code is smarter, this is just for CR
                raise Exception("FIXME: unhandle response")

    def finish(self):
        while self._pending:
            self.drain()
            if self._pending:
                time.sleep(1)

    def stop(self):
        for i in self._pending:
            try:
                i.cancel()
            except Exception as e:
                sys.stderr.write("Caught: " + str(e) + "\n")

        self._executor.shutdown()

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Perform all REST calls")
    parser.add_argument("--delay", type=int, default=0)
    parser.add_argument("urls", nargs="+")
    args = parser.parse_args()

    retriever = JSONRetriever()

    try:
        for url in args.urls:
            retriever.fetch(url)
            if args.delay > 0:  # may need a delay to rate limit requests
                time.sleep(args.delay)
                retriever.drain()  # clear any requests that completed while asleep

        retriever.finish()
    except KeyboardInterrupt:
        retriever.stop()


texts: Multi threaded application to send large no of emails

texts:
I need to build a application which sends a lot of emails. These emails are based on a table. Basic idea is, I grab a bunch of records from database. Create MailMessage (System.Net.Mail) and send it. Since there are a lot of mails to be sent, I am thinking about developing a multi-threaded application.

    public void Run()
    {
        var mailItems = MailItemDataProvider.GetLiveMailItems();
        if (mailItems.Count > 0)
        {
            var maxThreads = 5;
            var totalItems = mailItems.Count;
            int skipper = totalItems / (maxThreads - 1);
            if (skipper == 0)
                skipper = totalItems;

            for (var i = 0; i < totalItems; i += skipper)
            {
                var itemsLot = mailItems.Skip(i).Take(skipper).ToList();
                Task.Factory.StartNew(() => ProcessMails(itemsLot, ThreadPriority.Highest));
            }
        }
    }

It basically grabs a thousand records from the database and divide them into five chunks. The chunks are passed to the mail processor. The above function is triggered from a timer (Timer_Elapsed event) configured to run every minute. This is actually part of Windows Service. Mail processor is like this:

    protected void ProcessMails(IEnumerable<MailItem> mailItems)
    {
        foreach (var mailItem in mailItems)
        {
            bool errorFound;
            var mail = CreateMailMessage(mailItem, out errorFound);
            // returns (System.Net.Mail) MailMessage object

            if (!errorFound)
            {
                if (Mailer.SendEmail(mail))
                {
                    mailItem.StatusId = Status.Sent;
                }
                else
                {
                    mailItem.StatusId = Status.Failed;
                    mailItem.FailMessage = "Error sending email.";
                }
            }
            else
            {
                mailItem.StatusId = Status.Failed;
            }
        }
        UpdateMailItems(mailItems);
        // this updates mail sent status in the database
    }

In my test environment, it is working fine. I have tested for 100,000 emails.
Following are my concerns in the function that is processed by the threads:

What will happen when SMTP slows down (for some unknown reason)? I start up five threads, but it will add up five more before the first five complete. How many threads can my server handle? (I know it depends on actual resources available, but practically, how will it perform?)
I have database update inside the process. Is that good idea?
Is there a chance that some threads will never finish? Do I need to make sure that threads are completed? How do I detect the ever running threads and kill them?

I am new to multi threading. Please review my code. Any comments or suggestion are welcome.


texts: Allocating memory and releasing the same

texts:
I was going through a code snippet...

try
{
    ...
    // Memory is allocated here...
    NmsMessage* pNmsMessage = new NmsMessage(NMS_MODEM_DIAL_NUMBER);
    ...
    {
        // pNmsMessage is passed to another thread.
        pThis->m_pDeviceThread->PostThreadMessage(WM_NMS_MESSAGE, 0,pNmsMessage);
    }
    return NOERROR;
}
catch(...)
{
    ...
}

In the PostThreadMessage, memory pointed by pNmsMessage is getting released.

My question:

Is this the right way to handle memory in case of threaded environment?
If it is not threaded environment, is it better to release the memory before returning from the function and also in the catch block(I don't want to use smart pointers)?


texts:
I am writing a computer opponent in java to play the dice game pig. I am trying to code it to be optimized based off of this paper.

    @Override
public boolean decideIfShouldRoll(int turnNumber, int rollNumber,
        int poolSize, int myScore, int opponentsScore) {
    if (myScore < 30 && opponentsScore < 30) {
        if (poolSize <= 20)
            return true;
        else
            return false;
    }

    // Checks for if the opponent has a greater score
    if (opponentsScore > myScore) {

        // opponent is near winning?
        if (100 - opponentsScore <= 20) {

            // checks if computer is near winning
            if (100 - myScore <= 20) {
                if (poolSize <= 20)
                    return true;
                else
                    return false;
            }

            // if computer not near winning, take a go for broke strategy
            if (100 - myScore > 20) {
                if (poolSize <= 30)
                    return true;
                else
                    return false;
            }

        }
        if (opponentsScore > 20) {
            if (poolSize <= 20)
                return true;
            else
                return false;
        }

        return true;
    }

    if (myScore > opponentsScore) {

        // if near winning and the opponent's score is within 10 try a small
        // wins strategy
        if ((100 - myScore) <= 20 && (myScore - opponentsScore) <= 10) {
            if (poolSize <= 15)
                return true;
            else
                return false;
        }
        // if 10 points from winning, only build a pool up to 10 points
        if ((100 - myScore) <= 10) {
            if (poolSize <= 10)
                return true;
            else
                return false;
        }
        // if the difference between the computer score and opponent score
        // is > 10, go up to the standard optimal pool size of 20
        if ((myScore - opponentsScore) > 10) {
            if (poolSize <= 20)
                return true;
            else
                return false;
        }

        // if near winning and the opponents score is within 10 points, take
        // a reduced standard pool size
        if ((100 - myScore) <= 20
                && Math.abs(myScore - opponentsScore) <= 10) {

            if (poolSize <= 15)
                return true;
            else
                return false;
        }

        return true;
    }
    return true;

}


texts:
I recently posted an answer to this SO question as I did not think any of the current answers were satisfactory (most don't even answer the question!). I was wondering if anyone could offer any improvements on my solution to this problem? I'm most interested in performance here. Also note this algorithm does not require any additional copies of the input string (if passed an r-value), ideally I'd like to keep this property.

#include <string>
#include <cstdint>  // std::size_t
#include <cmath>    // std::floor, std::log2, std::pow
#include <iterator> // std::cbegin, std::cend, std::next

std::string repeatstring(std::string str, std::size_t n)
{
    if (n == 0) {
        str.clear();
        str.shrink_to_fit();
        return str;
    }

    if (n == 1 || str.empty()) return str;

    const auto repeat_size = str.size();

    if (repeat_size == 1) {
        str.append(n - 1, str.front());
        return str;
    }

    str.reserve(repeat_size * n);

    const auto m = static_cast<decltype(n)>(std::floor(std::log2(n)));

    for (auto i = m; i > 0; --i) str += str;

    n -= static_cast<decltype(n)>(std::pow(2, m));

    str.append(std::cbegin(str), std::next(std::cbegin(str), n * repeat_size));

    return str;
}

Here is an example:

#include <iostream>
#include <chrono>

int main()
{
    auto start = std::chrono::system_clock::now();

    auto str = repeatstring("helloworld", 190238011);

    auto end = std::chrono::system_clock::now();

    //std::cout << str << std::endl;
    std::cout << "string length: " << str.length() << std::endl;

    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);

    std::cout << "time: " << duration.count() << "ms" << std::endl;

    return 0;
}


texts:
I am brand new to writing my own code. I just started the CS50x intro class and have so far made it to pset 2 readability. It's getting easier to understand what's going on. I just wanted to get some opinions on the code that I wrote to see if there were possible improvements/changes that I could make.

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <math.h>

//initialize lenght function
int length(string str, char check);

int main(void)
{
    //Get user input
    string input = get_string("Text: ");

    //Calculate and set grade level. Take user input and run it thorugh the lenght function. l for letters, w for words and s for sentances.
    float gradeLevel = (0.0588 * (100 * (float) length(input, 'l') / (float) length(input, 'w')) - 0.296 * (100 * (float) length(input, 's') / (float) length(input, 'w'))) - 15.8;

    //output grade level
    if (round(gradeLevel) >= 16)
    {
        printf("Grade 16+\n");
    }

    else if (round(gradeLevel) < 1)
    {
        printf("Before Grade 1\n");
    }

    else
    {
        printf("Grade %i\n", (int) round(gradeLevel));
    }

    //print lengths for testing
    /*
    printf("%i letter(s)\n", length(input, 'l'));
    printf("%i word(s)\n", length(input, 'w'));
    printf("%i sentance(s)\n", length(input, 's'));
    */
}

//function to get length of letters, words and sentences
int length(string str, char check)
{
    int letterCount = 0;
    int wordCount = 1;
    int senCount = 0;
    int n = strlen(str);

//check letter count
    if (check == 'l')
    {
        for (int i = 0; i < n; i++)
        {
            if (isalpha(str[i]))
            {
                letterCount++;
            }
        }
        return letterCount;
    }
//check word count
    else if (check == 'w')
    {
        for (int i = 0; i < n; i++)
        {
            if (str[i] == ' ' || str[i] == '\n' || str[i] == '\t')
            {
                wordCount++;
            }
        }
        return wordCount;
    }
//check sentance count
    else if (check == 's')
    {
        for (int i = 0; i < n; i++)
        {
            if (str[i] == '.' || str[i] == '!' || str[i] == '?')
            {
                senCount++;
            }
        }
        return senCount;
    }
    return 0;
}

Thank you for the detailed feedback. Here's the specs of the program

Your program should count the number of letters, words, and sentences in the text. You may assume that a letter is any lowercase character from a to z or any uppercase character from A to Z, any sequence of characters separated by spaces should count as a word, and that any occurrence of a period, exclamation point, or question mark indicates the end of a sentence.

Your program should print as output "Grade X" where X is the grade level computed by the Coleman-Liau formula, rounded to the nearest integer.

If the resulting index number is 16 or higher (equivalent to or greater than a senior undergraduate reading level), your program should output "Grade 16+" instead of giving the exact index number. If the index number is less than 1, your program should output "Before Grade 1".

The algorithm used was the Coleman-Liau index


texts:
I've been unable to find a PHP function that will convert eol in files.  This is what I have so far. It works, no errors.

Your educated opinions, thoughts, improvements, potential bugs and suggestions are welcome.

/*
    $file_name - full/path/to/file.name

    $eol         - wanted end of line: "\n", "\r", "\r\n"
        from "\n" to "\r" || "\r\n"
        from "\r\n" to "\r" || "\n"
        from "\r" to "\n"

    $len    - buffer size

    return true on success or false on fail
*/
function file_eol($file, $eol, $len=8192) {

    $ok = FALSE;
    $extension = '.my_temp';

    $hread = FALSE;
    if (is_string($file))   $hread = fopen($file, 'rb');
    if ($hread === FALSE)   e("Bad file in file_eol(): $file");
    if (!is_resource($hread) || get_resource_type($hread) !== 'stream') e("Bad hread in file_eol(): $hread");

    $hsave = fopen($file.$extension, 'wb');
    if ($hsave === FALSE)       e("Bad hsave file in file_eol(): $file.my_temp");

    switch ($eol) {
    case "\n":      $order = array("\r\n", "\r");   // from "\r\n" || "\r" -> "\n"
    break;
    case "\r":      $order = array("\r\n", "\n");   // from "\r\n" || "\n" -> "\r"
    break;
    case "\r\n":    $order = array("\n", "\r\r\n"); // from "\n" -> "\r\n"
    break;

    default:
        e("Bad eol in file_eol(): $eol");
    }

    while (($str = fread($hread, $len)) && $str !== FALSE) {    // error or eof

        $new = str_replace($order, $eol, $str);
        // if (is_string($new)) $ok = fwrite($hsave, $new);     // this ???
        if ($new !== '')    $ok = fwrite($hsave, $new);
        if ($ok === FALSE) break;   //  or  e("Error writing file: $file$extension");
    }
    $ok = $ok === FALSE ? FALSE : TRUE; // ok could be valid 0bytes
    $ok = $ok && ((bool)$str || feof($hread));          // check if fread and feof failed
    $ok = $ok && fclose($hread) && fclose($hsave);  // ALWAYS check for fclose!

    if ($ok)    $ok = rename($file.$extension, $file);  // overwrite $file, and delete $file.$extension
    // else leave both files for later inspection

return $ok;
}

P.S. copy/paste should work if you create error handler function e() that will take string inputs or just change e() to trigger_error or whatever you want.

Edit:

Must include feof()

$ok = $ok && ((bool)$str || feof($hread));          // check if fread and feof failed


texts:
I'm currently doing an algorithms course and implemented this version of the quicksort algorithm. I would like to know if it is an efficient implementation. I've seen a couple others where there is a partition function that partitions the list is that a superior method to what I did?

def quickSort(aList):
    first = []
    second = []
    size = len(aList)
    if size ==0:
        return []
    elif size == 1:
        return aList
    elif size ==2:
        if(aList[1]<aList[0]):
            return list([aList[1],aList[0]])
        else:
            return aList
    else:
        key = aList[0]
        for i in range(1,size):
            if aList[i]<key:
                first.append(aList[i])
            else:
                second.append(aList[i])
        first.append(key)
    return quickSort(first) + quickSort(second)


texts:
In a previous post at Simplifying complex setf expressions, @sds suggested using the get-setf-expansion macro for implementing place modification, as discussed in On Lisp (p171ff) by Paul Graham . In a related post at Destructive place-modifying operators, @acelent provides additional guidance. Based on their advice, I've written a place modifying macro (below), and would appreciate any comments, improvements, corrections, or error checking procedures. It has passed the preliminary tests I have performed.  However, my experience with macros, is limited, and I know their workings can be subtle.

The macro is intended to perform (and return) an in-place modification based on an arbitrary common-lisp function. A simple example would be (! 1+ @x) == (incf x). The ! signifies modification, and @ indicates the place being modified (and returned). A more complex example is (! delete 3 @(car x) :test #'equal) == (setf (car x) (delete 3 (car x) :test #'equal)). I've had to include the @ marker for the place, since I can't think of another way to pass the place on to (get-setf-expansion place). (Is there any way to analyze the features of the input function in order to zero in on the appropriate place argument?) Otherwise, Paul Graham's macro template (he calls it _f) seems to work, if you substitute get-setf-expansion for his get-setf-method.

(defmacro ! (fn &rest args)
  "Modifies an object at a place according to a given function.
   Obviates the need for some specialized macros--eg, (incf x) == (! 1+ @x);
   and generalizes place modification for standard common-lisp functions."
  (let* ((sym (find-if #'(lambda (arg)  ;find the place argument signaled by @
                           (and (symbolp arg) (string= (aref (symbol-name arg) 0) "@")))
                       args))
         (fn-args (cond ((eq sym '@)  ;sym indicates a generalized reference
                         (remove '@ args))
                        ((> (length (symbol-name sym)) 1)  ;sym indicates a variable
                         (subst (find-symbol (subseq (symbol-name sym) 1)) sym args))
                        (t (error "Modify macro call ~A is ill-formed."
                                  (cons '! (cons fn args))))))
         (place (if (eq sym '@)
                    (elt args (1+ (position '@ args)))  ;generalized reference
                  (find-symbol (subseq (symbol-name sym) 1)))))  ;normal variable
    (multiple-value-bind (vars forms var set access)
        (get-setf-expansion place)
      ;(ut::prt fn args sym fn-args place vars forms var set access)
      (declare (ignore access))
      `(let* (,@(mapcar #'list vars forms)
                 (,(car var) (,fn ,@fn-args)))
         ,set))))


texts:
Here I am trying to simplify my bootstrap name using dot notation, but I'm having lots of issues getting my nav to render different pages.

Am I setting my routes properly?
Am I setting the switch properly?
Am I setting the Link properly?

I found most of my information here. I tried bringing in a switch on the App.js to help, and I tried bringing in a

HeaderNav

import React from "react";
import Nav from "react-bootstrap/Nav";
import { Link } from 'react-router-dom'

export default class HeaderNavigation extends React.Component {

      render() {
        return (
          <>
             alert(`selected ${selectedKey}`)}
            >

                 <Link to "/home">home</Link> Active

                Link

                Link

                  Disabled

          </>
        );
      }
    }

main.js

import React from "react";
import { Switch, Route } from "react-router-dom";
import Home from "./Home";
import Roster from "./Roster";
import Schedule from "./Schedule";

// The Main component renders one of the three provided
// Routes (provided that one matches). Both the /roster
// and /schedule routes will match any pathname that starts
// with /roster or /schedule. The / route will only match
// when the pathname is exactly the string "/"
const Main = () => (

    <Switch>
      <Route exact path="/home" component={Home} />
      <Route path="/about" component={Roster} />
      <Route path="/more" component={Schedule} />
    </Switch>

);

export default Main;

import React from "react";
import Jumbotron from "react-bootstrap/Jumbotron";
import main from "./src/main";

App.js

    / Importing the Bootstrap CSS
import "bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
import HeaderNavigation from "../src/HeaderNavigation";
import Form from "../src/Form";
import Body from "../src/Body";

const App = () => (
  <>
    <>
      <HeaderNavigation className="body" />

    </>
    <Jumbotron fluid>

Welcome To React-Bootstrap

    </Jumbotron>
    <Jumbotron fluid>
      <Form className="header" />
    </Jumbotron>

  </>
);

export default App;


texts: A fractal picture - John Zells graphics.py

texts:
This code generates a fractal picture. I'm experimenting with using long variable names to see if the code is still readable without comments. I'm a slow reader and loose track a lot and thought to myself why read twice (variable names and comments).

(When) is it better to replace comments with longer descriptive variable and function names?
Does this code make sense to you?
Would it be better off with comments?

from math import *
from graphics import *

def brushes(win, centerx, centery, brushmaximumradius):
    for brush in range(brushmaximumradius, 0, -1):
        spiralrevolutions = 10 * pi
        spiralanglevector = ((brushmaximumradius - brush) / brushmaximumradius * spiralrevolutions) ** 1.6
        spiralradius= (brushmaximumradius - brush) ** 0.8
        xaxistremble = (spiralradius / 10) * cos(spiralanglevector * 3)
        yaxistremble = (spiralradius / 10) * sin(spiralanglevector * 3)
        xkoordinat = int(spiralradius * cos(spiralanglevector) + xaxistremble) + centerx
        ykoordinat = int(spiralradius * sin(spiralanglevector) + xaxistremble) + centery
        c = Circle(Point(xkoordinat, ykoordinat), brush)
        c.setWidth(0)

        period = 1.3
        perioddisplacement = 0.15
        maximumlightintensity = 223
        lowestlightintensity = 22
        lightintensityatangle = int(sin(brush/brushmaximumradius*pi/2 * period + perioddisplacement) * maximumlightintensity + lowestlightintensity)

        amplitude = amplitudedisplacement = 0.5
        cirkelRGBred = int(lightintensityatangle * (sin(spiralanglevector) * amplitude + amplitudedisplacement))
        cirkelRGBgreen = int(lightintensityatangle * (sin(spiralanglevector + pi/2) * amplitude + amplitudedisplacement))
        cirkelRGBblue = int(lightintensityatangle * (sin(spiralanglevector + pi) * amplitude + amplitudedisplacement))
        c.setFill(color_rgb(cirkelRGBred, cirkelRGBgreen, cirkelRGBblue))
        c.draw(win)

windowwidth = 1350
windowheight = 730
win = GraphWin("My Circle", windowwidth, windowheight)
win.setBackground(color_rgb(55, 55, 55))

centerx = int(windowwidth / 2)
centery = int(windowheight / 2)
windowcornerfitting = 1.04
brushmaximumradius = int(windowcornerfitting * sqrt(centerx**2 + centery**2))

brushes(win, centerx, centery, brushmaximumradius)

win.getMouse()
win.close()


texts: Best practices to do complex forms with javascript?

texts:
In a Rails application, I want to have a complex form with some dynamic behaviour. For example, I want to show a part of the form want I check a box or I want to have different values in a select box when I choose a radio button.

I do this with JQuery. My problem concern the archirecture. I created a form object and I create a init method which init every behaviour of every components like this :

  PaintingForm.prototype.init = function() {
    var country_listener;
    if ($('form.painting').size() === 1) {
      this.form = $('form.painting').first();
      this.initImageUploader();
      this.initSubmit();
      this.assignInputs();
      this.initAutoComplete();
      this.listenCategories();
      country_listener = new CountryInputListener('#painting_country_id', '#painting_region_id');
      return country_listener.init();
    }
  };

  PaintingForm.prototype.initImageUploader = function() { //some code };

  PaintingForm.prototype.initSubmit = function() { //some code };

  PaintingForm.prototype.onSubmit = function() { //some code };

  PaintingForm.prototype.assignInputs = function() { //some code };

  PaintingForm.prototype.listenCategories = function() { //some code };

  PaintingForm.prototype.onCategoryInputChange = function() { //some code };

  PaintingForm.prototype.loadTechnics = function() { //some code };

  PaintingForm.prototype.showDepthIfSculptureChoosen = function() { //some code };

  PaintingForm.prototype.onLoadTechnicsSuccess = function() { //some code };

  PaintingForm.prototype.initAutoComplete = function() { //some code };

I'm not satisfied. I think I can split the form like this :

PaintingForm.prototype.init = function() {
  var country_listener;
  if ($('form.painting').size() === 1) {
    this.form = $('form.painting').first();
    (new PaintingForm.Category).init()
    (new PaintingForm.AutoComplete).init()
    (new PaintingForm.Depth).init()
    (new CountryInputListener('#painting_country_id', '#painting_region_id')).init();
  }
};

//other behaviour for the form

this.PaintingForm.Category = (function() {
  //Behaviour for categories
})();

this.PaintingForm.Depth = (function() {
  //Behaviour for depth
})();

this.PaintingForm.AutoComplete = (function() {
  //Behaviour for autocomplete
})();

It's better but I'm not sure. There is a lot of interactions between fields. Should I create one object for every fields? Is there a solution with a framework like or angular? Do you have correct examples?


texts: PHP Memento design pattern implementation

texts:
I am a self-taught programmer. I decided to learn design patterns by reading about them, and then coming up with their implementation in PHP. I know that learning would be virtually impossible without code review.

I will be grateful if you could review my implementation of the Memento design pattern and point to any shortcoming in the implementation of the pattern and general OOP principles.

My implementation tries to imitate the behaviour of a code repository (e.g. Git), where you can commit and checkout code based on previous commits. Below I present how a client can interact with the code.

/**
* Memento - a class that 'remembers' previous states
*/
class Repository
{
    /**
    * @var Commit[]
    */
    private $commits = [];

    /**
    * Commit objects are pushed into an array
    */
    public function saveCommit(Commit $commit)
    {
        array_push($this->commits, $commit);
    }

    /**
    * Rewind code to a selected commit by the commit key
    *
    * @param integer $commitKey The index key of a commit  to rewind code to
    * @return string Rewinded code
    */
    public function rewindCode($commitKey)
    {
        $rewindedCode = '';
        for($i=0; $i <= $commitKey; $i++) {
            $rewindedCode .= $this->commits[$i]->getCode();
        }
        return $rewindedCode;
    }

    public function getCommits()
    {
        return $this->commits;
    }

    /**
    * Get all commited code so far
    * @return string
    */
    public function getCommitedCode()
    {
        $commitedCode = '';
        foreach($this->commits as $commit) {
            $commitedCode .=  $commit->getCode();
        }
        return isset($commitedCode) ? $commitedCode : '';
    }
}

-

/**
* A class/data structure that represents a single commit
*/
class Commit
{
    private $timestamp;
    private $code;

    public function __construct($code)
    {
        $this->code = $code;
        $this->timestamp = time();
    }

    public function getCode()
    {
        return $this->code;
    }
}

-

/**
* Originator - a class that can save itself and retrieve states from the Memento object (Repository)
*/
class CodeBase
{
    private $repository;
    private $code;

    public function __construct(Repository $repo)
    {
        $this->repository = $repo;
    }

    public function writeCode($code)
    {
        $this->code = $this->code . $code;
    }

    /**
    * Extract code added since the last commit
    * @return string Code that has not yet been commited
    */
    private function getNewCode()
    {
        $commitedCode = $this->repository->getCommitedCode();
        return $newCode = str_replace($commitedCode, '', $this->code);
    }

    /**
    * Save state (code) to Memento (Repository)
    */
    public function commitToRepository()
    {
        $newCode = $this->getNewCode();
        $this->repository->saveCommit(new Commit($newCode));
    }

    /**
    * Rewind code to the selected commit (Retrieve saved state)
    */
    public function checkoutFromRepository($commitKey)
    {
        $this->code = $this->repository->rewindCode($commitKey);
    }

    public function getCode()
    {
        return $this->code;
    }

}

-

$repo = new Repository();
$codeBase = new CodeBase($repo);

$codeBase->writeCode('First day code');
$codeBase->writeCode('Second day code');
$codeBase->commitToRepository();
$codeBase->writeCode('Third day code');
$codeBase->commitToRepository();

$codeBase->checkoutFromRepository(0); // Roll back to the first commit
echo $codeBase->getCode(); // Prints: "First day code Second day code"

$codeBase->checkoutFromRepository(1); // Roll back to the second commit
echo $codeBase->getCode(); // Prints: "First day code Second day code Third day code"


texts: GroupBy field with and without white spaces

texts:
I have these invoices listed:

def invoices = [
'LEDES98BI V2',
'LINE|INVOICE_DATE|INVOICE_NUMBER|INVOICE_TOTAL',
'1|20150301|INV-Error_Test1|22',
'2|20150301|INV-Error_Test1|24',
'3|20150301|INV-Error_Test2|26',
'4|20150301|INV-Error_Test2|28,']

I am trying to do groupBy on the above collection with INVOICE_NUMBER and trying to achieve map with INVOICE_NUMBER and lines as values:

def lines = invoices*.split('\\|').findAll{ it.size()>1 }
def heads = lines.first()
def invoiceMap =  lines.tail().collect{ [heads, it].transpose().collectEntries() }.groupBy{ it.INVOICE_NUMBER }

If I print invoiceMap I get what I intended as this map:

 [INV-Error_Test1:[[LINE:1, INVOICE_DATE:20150301, INVOICE_NUMBER:INV-Error_Test1, INVOICE_TOTAL:22],
                   [LINE:2, INVOICE_DATE:20150301, INVOICE_NUMBER:INV-Error_Test1, INVOICE_TOTAL:24]],
  INV-Error_Test2:[[LINE:3, INVOICE_DATE:20150301, INVOICE_NUMBER:INV-Error_Test2, INVOICE_TOTAL:26],
                   [LINE:4, INVOICE_DATE:20150301, INVOICE_NUMBER:INV-Error_Test2, INVOICE_TOTAL:28,]]
  ]

But if the INVOICE_NUMBER has any white spaces with it in the invoices map my code doesn't work, so I tweaked the code as below to get it working:

 def invLineDetails = lines.tail().collect{ [heads, it].transpose().collectEntries() }.groupBy{it[it.keySet().find{it.contains('INVOICE_NUMBER')}] }

Can this code be optimized/refactored further?


texts:
Q1. Define a function reverse_list that takes a list as an argument
  and returns None, but reverses the elements in the list as a side
  effect. Do not use any built-in list methods (especially not reverse),
  but assignment statements are fine.

Below is the iterative solution:

def reverse_list_iter(s):
    """Reverse the contents of the list s and return None.

    >>> digits = [6, 2, 9, 5, 1, 4, 1, 3]
    >>> reverse_list_iter(digits)
    >>> digits
    [3, 1, 4, 1, 5, 9, 2, 6]
    >>> d = digits
    >>> reverse_list_iter(d)
    >>> digits
    [6, 2, 9, 5, 1, 4, 1, 3]
    """
    median = len(s)//2
    length = len(s)
    for index in range(median):
        temp = s[index]
        s[index] = s[(length - 1) - index]
        s[(length - 1) - index] = temp

Below is the recursive solution:

def reverse_list_recur(s):
    """Reverse the contents of the list s and return None.

    >>> digits = [6, 2, 9, 5, 1, 4, 1, 3]
    >>> reverse_list_recur(digits)
    >>> digits
    [3, 1, 4, 1, 5, 9, 2, 6]
    >>> d = digits
    >>> reverse_list_recur(d)
    >>> digits
    [6, 2, 9, 5, 1, 4, 1, 3]
    """
    median = len(s)//2
    length = len(s)
    def reverse(index):
        if index == median:
            return
        else:
            temp = s[index]
            s[index] = s[(length - 1) - index]
            s[(length - 1) - index] = temp
            reverse(index + 1)
    reverse(0)

How can I improve the solution?


texts: Find MIDI devices with certain names and make them usable

texts:
I'm working on a Swift app for macOS, where I take input from MIDI devices and transform that input. The MIDI devices being supported come in for flavors.

What my code does is scan for MIDI devices, filter all the MIDI devices to only leave the ones I want, initiates classes on them and puts them in a array.

However, what I'm wondering is, does my code do this efficiently, or is there a better/more (memory?) efficient way to do this?

import Cocoa
import CoreMIDI

class DeviceManager {
    var connectedDevices : [String : DeviceProtocol] = [ : ]
    let deviceNames : [String] = [
        "wob",
        "wiggle",
        "drum",
        "scan"
    ]

    /**
     * Constructor: Scan for devices.
     */
    init() {
        self.scan()
    }
    /**
     * Scan for OWOW midi devices. Initiate classes on them.
     */
    func scan() {
        let allDestinations : [MIDIEndpointRef : String] = getSourceNames()

        for (midiReference, name) in allDestinations {
            for deviceName in self.deviceNames {
                if name.lowercased().range(of: deviceName) != nil {
                    var device : (Any)? = nil
                    switch name.lowercased() {
                    case "wob" :
                        device = Wob(src: midiReference)

                    case "wiggle" :
                        device = Wiggle(src: midiReference)

                    case "scan" :
                        device = Scan(src: midiReference)

                    case "drum" :
                        device = Drum(src: midiReference)

                    default :
                        device = nil
                    }

                    self.connectedDevices[formatDisplayName(name: name)] = device as? DeviceProtocol
                }
            }
        }
    }

    /**
     * Remove other keywords (e.g. bluetooth) from the name of the device.
     *
     * @param String name: The name we wish to format.
     * @return String: The formatted name.
     */
    private func formatDisplayName(name : String) -> String {
        let nameList = name.characters.split {$0 == " "}

        return String(nameList[0])
    }

    /**
     * Format the displayname of a MIDI device to something we can actually use.
     *
     * @param MIDIObjectRef object: A midi object
     * @return String: The name of the device.
     */
    private func getDisplayName(_ object: MIDIObjectRef) -> String {
        var param : Unmanaged<CFString>?
        var name : String = ""

        let error : OSStatus = MIDIObjectGetStringProperty(object, kMIDIPropertyDisplayName, &param)

        if error == OSStatus(noErr) {
            name = param!.takeRetainedValue() as String
        }

        return name
    }

    /**
     * Get a list of all MIDI sources.
     *
     * @return [MIDIEndpointRef : String]: A dictionary of all midi endpoints.
     */
    private func getSourceNames() -> [MIDIEndpointRef : String] {
        var names : [MIDIEndpointRef : String] = [:]

        let midiCount : Int = MIDIGetNumberOfDestinations()

        for i in 0..<midiCount {
            let endpoint : MIDIEndpointRef = MIDIGetSource(i)
            if endpoint != 0 {
                names[endpoint] = getDisplayName(endpoint)
            }
        }

        return names;

    }

    /**
     * Return a dictionary of connected devices/
     *
     * @return [String : DeviceProtocol] : A dictionary of connected OWOW devices.
     */
    func getConnectedDevices() -> [String : DeviceProtocol] {
        return self.connectedDevices
    }
}


texts:
I have a physical robot which has a function, turn(degrees). For different robots, there will be small differences in the accuracy of the turn. I have fine turning variables, multiplier and adder. The degrees are multiplied by the multiplier, and then adder is added on.

I have made a program to brute-force the optimal values for fine tuning. The program is very simple, unoptimized, and slow.

The code:

from datetime import datetime

# in the format (request degrees, actual degrees)
real_results = (
(90, 99),
(100, 109),
(110, 121),
(125, 140),
(130, 149),
)
max_adder = 100
max_multiplier = 100
precision = 0.01

#        amount off, adder, multiplier
best_setting = [9999, 0, 0]

start_time = datetime.now()
# this lets me "step" in precision increments, because range only accepts
# integers, I tried making my own function but it was 3 times slower
# stackoverflow.com/questions/7267226
for adder in range(int(max_adder / precision)):
    for multiplier in range(int(max_multiplier / precision)):
        amount_off = 0
        for result in real_results:
            # the * precision turns it from an integer into steps of 0.01
            amount_off += abs(
                result[0] * (multiplier*precision) + (adder*precision) - result[1])
        if amount_off < best_setting[0]:
            best_setting[0] = amount_off
            best_setting[1] = adder
            best_setting[2] = multiplier

print("Best settings are:")
print("adder: {:0.3f}".format(1 / (best_setting[1] * precision) if best_setting[1] else 0))
print("multiplier: {:0.3f}".format(1 / (best_setting[2] * precision) if best_setting[2] else 0))
print("Average amount off: {:.4f}".format(best_setting[0] / len(real_results) if best_setting[0] else 0))
print("That run took:", datetime.now() - start_time)

How can I make my program faster?
The idea I currently have is having the second for loop (adder) could start in the middle, and act like a basic P controller. I'll work on this while I wait for replies :)

Clarification:

The data set will be manually created by someone requesting a turn, and recording what the actual turn was. This means the data set will usually be around 4 to 8 results long.

The precision is how accurate we want the result to be. Ideally it would be as precise as possible, but since the robot has a fair amount of unpredictability, 2 d.p is fine.

The program finds the number that the results were multiplied by. In order to find the number that will give the most accurate turn, we must divide 1 by the number.

numpy.arange: yes, I should have used that because that is exactly what my code emulates. I didn't know about that yesterday :P


texts:
I use this code to check that all files in a directory are free from Unicode and non-printable characters.

Can I improve the structure of the code?

#!/usr/bin/env python3

import argparse
import os
import string
import sys

def main(input_folder):
    for directory, subdirs, files in os.walk(input_folder):
        for basename in files:
            path = os.path.join(directory, basename)
            try:
                check_file(path)
            except (ValueError, UnicodeDecodeError) as e:
                print(e)
                sys.exit(1)
    print('All files are ok!')

def check_file(path):
    with open(path, encoding='utf-8') as fp:
        try:
            data = fp.read()
        except UnicodeDecodeError:
            raise ValueError('Warning! {} contains non ascii characters'.format(path))
        if not is_printable(data):
            raise ValueError('Warning! {} contains non printable characters'.format(path))

def is_printable(s):
    return all(c in string.printable for c in s)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Verify correctness of files.')
    parser.add_argument('--input', required=True, help='Input folder')
    args = parser.parse_args()
    main(args.input)


texts:
In my application, I am using UserDefaults to save some data.
I also started writing tests for testing my application code.
At one place I stuck where I wanted to write tests for functions which are saving data to UserDefaults.
When I wrote tests with fake data, my actual data got overwritten by fake data.

So I choose to use Mocking for UserDefaults as follow:

This is controller class which manages saving and fetching data from UserDefaults:

UserDefaultsController-

protocol UserDefaultsProtocol: class {
    func theObject(forKey key: String) -> Any?
    func setTheObject(_ object: Any, forKey key: String)
    func removeTheObject(forKey key: String)
    func synchronizeAll()
}

class UserDefaultsController: NSObject {
    static let shared = UserDefaultsController()
    var delegate: UserDefaultsProtocol?

    override init() {
        super.init()
        //default delegate
        delegate = UserDefaults.standard
    }

    func object(forKey key: String) -> Any? {
        return delegate?.theObject(forKey: key)
    }

    func set(_ value: Any, forKey key: String) {
        delegate?.setTheObject(value, forKey: key)
    }

    func removeObject(forKey key: String) {
        delegate?.removeTheObject(forKey: key)
    }

    func synchronize() {
        delegate?.synchronizeAll()
    }
}

Here is UserDefault class extension which conforms protocol as:

extension UserDefaults: UserDefaultsProtocol {

    func theObject(forKey key: String) -> Any? {
        return self.object(forKey: key)
    }

    func setTheObject(_ object: Any, forKey key: String) {
        self.set(object, forKey: key)
    }

    func removeTheObject(forKey key: String) {
        self.removeObject(forKey: key)
    }

    func synchronizeAll() {
        self.synchronize()
    }
}

Whenever I want to interact with UserDefaults, I do it th’r above class as, e.g.:

UserDefaultsController.shared.set("test.com", forKey: “DomainNameKey”)

It is working fine, no issue at all!

Now, when I write tests, I use mock object to conform to UserDefaultsProtocol as:

class UserDefaultsMock: NSObject, UserDefaultsProtocol {

    private var dict = [String: Any?]()

    deinit {
        dict.removeAll()
    }

    //MARK: - Protocol Methods -
    func theObject(forKey key: String) -> Any? {
        if let object = dict[key] {
            return object
        }
        return nil
    }

    func setTheObject(_ object: Any, forKey key: String) {
        dict[key] = object
    }

    func removeTheObject(forKey key: String) {
        dict.removeValue(forKey: key)
    }

    func synchronizeAll() {
        //none
    }
}

And here is actual test:

class ArrayTests: XCTestCase {

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
        UserDefaultsController.shared.delegate = UserDefaultsMock()
        UserDefaultsController.shared.set("test.com", forKey: “DomainNameKey”)
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        UserDefaultsController.shared.delegate = nil
        super.tearDown()
    }

    func testFunction() {
        XCTAssertEqual(someFunctionWhichInteractsWithUserDefaults())
    }
}

Now my test is not overwriting anything on my actual data, works perfect!
But my worry is, I need to write all the UserDefault APIs like string(forKey), int(forKey), etc in protocol, controller class, and in UserDefault extension and mock.

Is this is the way it should be Or am I missing any other approach on testing UserDefaults?

My only worry is because every time in my app I have to use UserDefaultsController instead of UserDefaults!


texts: Given two words, transform the first one into the second

texts:
As the title says, the problem I had to do sounded something like this:
We are given two words, S1 and S2. We must transform S1 into S2, using the following operations:

insert: insert a character in S1 on whichever index you wish.
delete: delete a character from S1 from whichever index you wish.
replace: replace a character from S1, with whatever character you wish, on whatever index you wish.

All the operations have a cost of 1. At the end of the program, the total cost of all the operations must be minimum, therefore we must use as few operations as possible.
Example:
S1="carte"
S2="antet"
first operation: delete 'c' at index 0 ; -> S1 = arte
second operation: replace 'r' with n; -> S1 = ante
third operation: add 't' at the end of S1; -> S1=antet

Therefore, we have a total cost of 3.
Here is my code for it:
    package project3;

import java.util.*;

public class Main {
    static String S1 = "antetlllll";
    static String S2 = "antet";

    public static void main(String[] args) {
        StringBuilder sb;
        int c = 0;

        for (int i = 0; i < S2.length(); i++)
            if (i<S1.length())// we make sure that S1 is at least as big as S2
                if(S1.charAt(i)!=S2.charAt(i)){
                if ((i < S1.length() - 1) && (S1.charAt(i + 1) == S2.charAt(i) ) && (S1.charAt(i + 1) != S2.charAt(i+1) ) ) {  // if the char on the next position of S1 is the char we need, we delete the original one
                    sb = new StringBuilder(S1);
                    sb.deleteCharAt(i);
                    S1 = sb.toString();
                    c++;
                }
                else {  // else, we simply replace it
                    sb = new StringBuilder(S1);
                    String S = "";
                    S = S + S2.charAt(i);
                    sb.replace(i, i+1, S);
                    S1 = sb.toString();
                    c++;
                } }
            else
                if(S1.charAt(i) != S2.charAt(i))
                {  // if S1 is smaller than S2, we simply insert the needed characters into S1
                    sb = new StringBuilder(S1);
                    sb.insert(i, S2.charAt(i));
                    S1 = sb.toString();
                    c++;
                }

        if (S1.length() > S2.length()) {  // at this point S1 has a substring S2 in it. We just remove the extra letters from it.

            int n = S1.length();
            for (int i = S2.length(); i < n; i++) {
                sb = new StringBuilder(S1);
                sb.deleteCharAt(S2.length());
                S1 = sb.toString();
                c++;
            }

        }

        if (S1.length() < S2.length()) {  // at this point S1 has most of S2 characters. We just add the ones still needed.

            int n = S1.length();
            for (int i = n; i < S2.length(); i++) {
                sb = new StringBuilder(S1);
                sb.insert(i,S2.charAt(i));
                S1 = sb.toString();
                c++;
            }

        }

        System.out.println(c);
        System.out.println(S1);
    }

}

Note that when I say things like "S1 bigger than S2", I refer to their lengths.
So I had this problem as an assignment for school, and one of the requirements was that it had to be done using dynamic programming and it had have a complexity of O(m × n) (m=length of S1 ; n=length of S2) at most. Now, I'm new to DP, started doing it today after a bit of research, so I'd like to know if my code meets the two requirements I had.


texts: Find all permutations of a string in C++

texts:
I need a review of the following code for finding all permutations of a string in C++:

List Permute(const String& string)
{
    if (string.length == 0)
        return EmptyStrings(1);
    List prevList = Permute(SubString(string,1,string.length));
    List nextList = EmptyStrings(string.length*prevList.length);
    for (int i=0; i<prevList.length; i++)
    {
        for (int j=0; j<string.length; j++)
        {
            nextList[i*string.length+j] += SubString(prevList[i],0,j);
            nextList[i*string.length+j] += string[0];
            nextList[i*string.length+j] += SubString(prevList[i],j,string.length-1);
        }
    }
    return nextList;
}

You may assume the correctness of the following:

class List
class String
List EmptyStrings(int n); // returns a list of 'n' empty strings
String SubString(const String& string,int i,int j); // returns the string 'string[i...j)'


texts: Exponentiation by squaring in x64 Linux Assembly

texts:
I am learning some assembly for a compiler project I am working on and I have come across the Exponentiation by Squaring algorithm when it came to calculating x ^ n. To get a grasp on how the algorithm works before I add the operation to my code generation, I have written it out to see if it works.
Is my code optimum? and can it be improved on (such as reducing the number of line needed and efficiency?)
I am assembling with nasm and I am running on x86_64 linux
;   Function exp_by_squaring_iterative(x, n)
_ipow:
   ; set the x and y values
   mov r8, 50 ; x
   mov r9, 10 ; n

   ; check if n is 1
   cmp r9, 1         ; compare n with 1
   je _equalsOne     ; goto equalsone if n is 1
   jne _notEqualsOne ; goto noequalsone if n is not 1

; return 1
_equalsOne:
   mov rax, r8
   ret         ; if n equals 1 return x

;     if n < 0 then
_notEqualsOne:
   cmp r9, 0       ; compare n with 0
   jl _lessthan    ; goto lessthan zero if x is less than zero
   jnl _equalszero ; goto equalszero if n is equal to zero

_lessthan:
;       x := 1 / x;
;       n := -n;
   xor rdx, rdx ; zero rdx
   mov rax, 1  ; move 1 to rax
   div r8      ; divide 1 / x
   mov r8, rax ; move x back to r8
   not r9      ; revers ns bits

;     if n = 0 then return 1
_equalszero:
   cmp r9, 0   ; compare n with zero
   je _ezero   ; go to ezero if n equals zero
   jne _nzero  ; go to nzero if n is not zero

_ezero: ; return 1
   mov rax, 1  ; set rax as 1
   ret         ; return 1 if n is 0

;     y := 1;
_nzero:
   mov r10, 1 ; set r10 as 1, y

_loop1:
   mov rax, r9  ; move n to rax
   test al, 1   ; check if n is an odd number by testing the low bit
   jz  _even    ; jump if even = lowest bit clear = zero
   jnz _odd     ; jump if odd  = lowest bit set

;       if n is even then
_even:
;         x := x * x;
   mov rax, r8 ; move x to rax
   mul rax     ; multiply x by itself
   mov r8, rax ; move x back to r8

;         n := n / 2;
   mov rbx, 2  ; 2 to rbx
   mov rax, r9 ; move n to rax
   div rbx     ; divide n by 2
   mov r9, rax ; move n back

   jmp _condition ; jump over odd since if even, was processed

; n is an odd number
_odd:
;         y := x * y;
   mov rax, r10 ; move y to rax
   mul r8   ; multiply y by x
   mov r10, rax ; move y back to r10

;         x := x * x;
   mov rax, r8 ; mov x to rax
   mul rax  ; multiply x by itself
   mov r8, rax ; mov x back to r10

;         n := (n – 1) / 2;
   mov rax, r9 ; mov n to rax
   sub rax, 1  ; minus 1 from n
   mov rbx, 2  ; set rbx as 2
   div rbx     ; divide n by 2
   mov r9, rax ; move n back to rax

;     while n > 1 do
_condition:
   cmp r9, 1   ; compare r9 with 1
   jg _loop1   ; if 1 is greater than 1 then loop

;     return x * y
   mov rax, r8 ; move x to rax
   mul r10     ; multiple x and y
   ret         ; return


texts:
The code below solves the following task

Find the maximum price change over any 1 to 5 day rolling window, over a 1000 day period.

To be clear "any 1 to 5 day rolling window" means t[i:i + j] where j can range from 1 to 5. Rather than t[i:i + 5] if it were just "any 5 day rolling window".
I used NumPy native functions to do this. But I've used a for-loop for the inner iteration.
import numpy as np
import numpy.random as npr

prices = npr.random([1000,1])*1000

max_array = np.zeros([(prices.size-5),1])
for index, elem in np.ndenumerate(prices[:-5,:]):
    local_max = 0.0
    for i in range(1,6,1):
        price_return = prices[(index[0] + i),0] / elem
        local_max = max(local_max, price_return)
    max_array[index[0]] = local_max
global_max = np.amax(max_array)

Can I somehow eliminate the inner for loop and use NumPy vectorization instead?
I also don't particularly like using "index[0]" to extract the actual index of the current loop from the tuple object that is returned into the variable "index" via the call:

for index, elem in np.ndenumerate(prices[:-5,:]):


texts: Comparing two cars via their lifetime price

texts:
I am currently using the Udacity Introduction to Java course. There was a topic on Algorithms and it gave an example Algorithm for comparing and purchasing two different cars in pseudo code. I decided to turn that into some Java code to see just how well I grasped the concept.

The algorithm was:

  For each car, compute. Gas cost = (miles driven / mpg) * price per
  gallon. Total cost = gas cost + car cost. If car 1 < car 2, buy car 1.
  Else, buy car 2.

//Algorithm for buying a car
//by comparing car price, MPG,
//local gas price, and the miles
//to be drive in total.
//idea from udacity Intro
//to Java course.

import java.util.Scanner;

public class buyingCars {

     public static void main (String[] args) {

            Scanner input = new Scanner(System.in);

            System.out.println("Enter the price of car one: ");
            int carOnePrice = input.nextInt();

            System.out.println("Enter the price of car two: ");
            int carTwoPrice = input.nextInt();

            System.out.println("Enter the price of gas in your area: ");
            double gasPrice = input.nextDouble();

            System.out.println ("What is the average mpg of car one? ");
            int carOneMpg = input.nextInt();

            System.out.println ("What is the average mpg of car two? " );
            int carTwoMpg = input.nextInt();

            System.out.println("Give me an amount of miles total you think you will drive in this car: ");
            int milesDriven = input.nextInt();

            double gasCostCarOne = (milesDriven / carOneMpg) * gasPrice;
            double totalCostCarOne = gasCostCarOne + carOnePrice;

            double gasCostCarTwo = (milesDriven / carTwoMpg) * gasPrice;
            double totalCostCarTwo = gasCostCarTwo + carTwoPrice;

            if (totalCostCarOne < totalCostCarTwo) {

                    System.out.println("Car One will, in total, cost less than car two. Buy it.");
            }

            else {

                    System.out.println("Car two will, in total, cost less than car one. Buy it.");
            }
      }
}

What I am wondering is if my code was clean and my form is good? Are there things I am doing in my code that I should not be, or is everything looking pretty solid?

Also, is there a simpler way of doing this? It just seems like an awful lot of code that could potentially be narrowed down. Could each car hold it's values in an array or something like that?

If there is a problem with my post, please let me know. I am still getting use to posting here.


texts:
I am trying to implement an efficient collision detection between a line joining two points and a bitmap mask.

Example:

Currently I am using Bresenham's line drawing algorithm to draw each pixel of the line between the two points and comparing that pixel with the bitmap (If the pixel is black return true else continue drawing the line).

collision(x0,y0,x1,y1) {
  let dx = Math.abs(x1 - x0),
    dy = Math.abs(y1 - y0),
    sx = (x0 < x1) ? 1 : -1,
    sy = (y0 < y1) ? 1 : -1,
    err = dx - dy,
    e2

  // loop through line drawing
  while (!((x0 == x1) && (y0 == y1))) {
    e2 = err << 1;
    // check line point x,y against bitmap
    if (bitmap[x0][y0] == 1) {
      return 1;
    }
    if (e2 > -dy) {
      err -= dy;
      x0 += sx;
    }
    if (e2 < dx) {
      err += dx;
      y0 += sy;
    }
  }
  // If looped through whole line and not returned collision return false
  return 0
}

Is this a good/efficient approach? Or is there a set method or better approach for this problem?

Thanks in advance.


texts: Understanding OO JavaScript with a simple scenario

texts:
Coming from a Java kind of OOP, I miss a lot of things in JavaScript. I am working on a Node.Js project, and I would like to use an OO approach.

Looking around and asking in StackOverflow I came up with this example scenario (jsFiddle).

function inheritPrototype(childObject, parentObject) {
    var copyOfParent = Object.create(parentObject.prototype)
    copyOfParent.constructor = childObject
    childObject.prototype = copyOfParent
}

//example
function Canvas (id) {
    this.id = id
    this.shapes = {} //instead of array?
    console.log("Canvas constructor called "+id)
}
Canvas.prototype = {
    constructor: Canvas
    , getId: function() {
        return this.id
    }
    , getShape: function(shapeId) {
        return this.shapes[shapeId]
    }
    , getShapes: function() {
        return this.shapes
    }
    , addShape: function (shape)  {
        this.shapes[shape.getId()] = shape
    }
    , removeShape: function (shapeId)  {
        var shape = this.shapes[shapeId]
        if (shape)
            delete this.shapes[shapeId]
        return shape
    }
}

function Shape(id) {
    this.id = id
    this.size = { width: 0, height: 0 }
    console.log("Shape constructor called "+id)
}
Shape.prototype = {
    constructor: Shape
    , getId: function() {
        return this.id
    }
    , getSize: function() {
        return this.size
    }
    , setSize: function (size)  {
        this.size = size
    }
}

//inheritance
function Square(id, otherSuff) {
    Shape.prototype.constructor.apply( this, arguments );
    this.stuff = otherSuff
    console.log("Square constructor called "+id)
}
inheritPrototype(Square, Shape)
Square.prototype.getSize = function() { //override
    return this.size.width
}

function ComplexShape(id) {
    Shape.prototype.constructor.apply( this, arguments );
    this.frame = null
    console.log("ComplexShape constructor called "+id)
}
inheritPrototype(ComplexShape, Shape)
ComplexShape.prototype.getFrame = function() {
    return this.frame
}
ComplexShape.prototype.setFrame = function(frame) {
    this.frame = frame
}

function Frame(id) {
    this.id = id
    this.length = 0
}
Frame.prototype = {
    constructor: Frame
    , getId: function() {
        return this.id
    }
    , getLength: function() {
        return this.length
    }
    , setLength: function (length)  {
        this.length = length
    }
}

/////run
var aCanvas = new Canvas("c1")
var anotherCanvas = new Canvas("c2")
console.log("aCanvas: "+ aCanvas.getId())

var aSquare = new Square("s1", {})
aSquare.setSize({ width: 100, height: 100})
console.log("square overridden size: "+aSquare.getSize())

var aComplexShape = new ComplexShape("supercomplex")
var aFrame = new Frame("f1")
aComplexShape.setFrame(aFrame)
console.log(aComplexShape.getFrame())

aCanvas.addShape(aSquare)
aCanvas.addShape(aComplexShape)
console.log("Shapes in aCanvas: "+Object.keys(aCanvas.getShapes()).length)

anotherCanvas.addShape(aCanvas.removeShape("supercomplex"))
console.log("Shapes in aCanvas: "+Object.keys(aCanvas.getShapes()).length)
console.log("Shapes in anotherCanvas: "+Object.keys(anotherCanvas.getShapes()).length)

console.log(aSquare instanceof Shape)
console.log(aComplexShape instanceof Shape)

Is this approach correct (best practices)? Should I do something differently?

The idea would be then to create a js file for each class and use module.exports.. in Node.Js I will also use Mongoose to store the objects into a database, I guess I will need a way to translate my objects into Mongoose Models and back..

EDIT: how would one implement private methods used internally?


texts:
def draw_dashed_line(surf, color, start_pos, end_pos, width=1, dash_length=10):
    x1, y1 = start_pos
    x2, y2 = end_pos
    dl = dash_length

    if (x1 == x2):
        ycoords = [y for y in range(y1, y2, dl if y1 < y2 else -dl)]
        xcoords = [x1] * len(ycoords)
    elif (y1 == y2):
        xcoords = [x for x in range(x1, x2, dl if x1 < x2 else -dl)]
        ycoords = [y1] * len(xcoords)
    else:
        a = abs(x2 - x1)
        b = abs(y2 - y1)
        c = round(math.sqrt(a**2 + b**2))
        dx = dl * a / c
        dy = dl * b / c

        xcoords = [x for x in numpy.arange(x1, x2, dx if x1 < x2 else -dx)]
        ycoords = [y for y in numpy.arange(y1, y2, dy if y1 < y2 else -dy)]

    next_coords = list(zip(xcoords[1::2], ycoords[1::2]))
    last_coords = list(zip(xcoords[0::2], ycoords[0::2]))
    for (x1, y1), (x2, y2) in zip(next_coords, last_coords):
        start = (round(x1), round(y1))
        end = (round(x2), round(y2))
        pygame.draw.line(surf, color, start, end, width)

This function takes two coordinates and draws a colored dashed line from the first to the second coordinate. Line a = abs(x2 - x1) to line dy = dl * b / c calculates the amount x and y change for dl (dash_length).
Because dx and dy are floats, I had to use numpy.arange (built-in range() doesn't allow floating-point).

Here's an example:

draw_dashed_line(screen, RED, (0, 0), (800, 600), dash_length=5)

Documentation for pygame.draw.line:
http://www.pygame.org/docs/ref/draw.html#pygame.draw.line


texts:
The challenge, from Tour of Go, "Exercise: HTTP Handlers":

  Implement the following types and define ServeHTTP methods on them. Register them to handle specific paths in your web server.

type String string

type Struct struct {
    Greeting string
    Punct    string
    Who      string
}

For example, you should be able to register handlers using:

http.Handle("/string", String("I'm a frayed knot."))
http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"})

Solution:

package main

import (
    "log"
    "net/http"
    "fmt"
)

type String string

type Struct struct {
    Greeting    string
    Punct       string
    Who         string
}

func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if _, err := fmt.Fprint(w, s); err != nil {
        log.Fatal("Error in ServerHTTP of String.")
    }
}

func (s *Struct) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if _, err := fmt.Fprint(w, s.Greeting, s.Punct, s.Who); err != nil {
        log.Fatal("Error in ServerHTTP of String.")
    }
}

func main() {
    http.Handle("/string", String("I'm a frayed knot."))
    http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"})
    log.Fatal(http.ListenAndServe("localhost:4000", nil))
}

Any suggestions on how to improve this code?


texts: Find list of valid continuing positions in a game

texts:
My kids got a dice game for Christmas. I'm trying to mathematically analyze it. The first step is to come up with a list of all possible positions.

Each player in the game has a certain number of chips. A valid position is when more than one player has chips. If only one player has chips, they win and the game is over -- that's easy to identify.

I'm trying to come up with sensible code that uniquely lists all non-terminating positions. I use flatten() from more_itertools which is in PIP. Here's what I've got:

from more_itertools import flatten
from itertools import permutations

def all_nonzero_positions(num_players, num_chips, min_chips, max_chips):
    """ Returns all monotonically descending lists
        where num_chips are divided among num_players
        with each player having at least one chip, subject to the
        min_chips and max_chips constraints. Recursive. """
    if num_players==1:
        return [[num_chips]] if min_chips <= num_chips <= max_chips else []
    return [[p1] + y for p1 in range(min_chips,max_chips+1)
            for y in all_nonzero_positions(num_players-1, num_chips-p1,min_chips,p1)]

def all_positions_sorted(num_players, num_chips):
    """ Returns all monotonically descending lists
        where num_chips are divided among num_players
        where at least two players have one or more chips.
        Works by repeatedly calling all_nonzero_positions()
        for smaller num_players and appending necessary zero elements. """
    return [position + [0]*zeroes for zeroes in range(0,num_players-1)
            for position in all_nonzero_positions(num_players-zeroes,num_chips,1,1000)]

def all_valid_positions(num_players, num_chips):
    return set(flatten(list(permutations(x))
                       for x in all_positions_sorted(num_players,num_chips)))

def main():
    print(*all_valid_positions(3,3), sep='\n')

if __name__ == "__main__":
    main()

What I don't like:

The lines are too long, but I don't see any place I can create temp variables or functions.
Can I get rid of more_itertools.flatten() without lengthening the code?
Can I get rid of list(), which I'm using to instantiate the generator?
Can I get rid of set(), which I'm using to trim the duplicates?
Is there a better way to permute than using itertools.permutations()?
Can all_nonzero_positions() be written without recursion?
I'm creating a ton of temporary lists here, can that be reduced?
What other comments should I add? The code is really short, I don't know where to put them.


texts:
The idea may sound stupid, but this is what I got to know that you should take a break at regular intervals to not to strain your eyes.

So the idea is to take break of 2 minutes for every 20 minutes of work and a break of 10 minutes for every one hour. People when working sometimes works continuously without monitoring the amount of time they spend on a single stretch. Hope this make some sense and reason for developing it in python is to improve my coding skills.

#cat lock_sys.py
import time
import subprocess

TIME = 20
BREAK1 = 2
BREAK2 = 10
COUNT = 3

def verify_pkg():

    #check if package is installed on the server
    check_pkg = subprocess.Popen(["apt", "-qq", "list", "gnome-screensaver"], stdout=subprocess.PIPE)
    pkg_avil = "installed" in check_pkg.communicate()[0]

    #if not installed, install the package
    if not pkg_avil:

        install_pkg = subprocess.Popen(["apt-get", "install", "-y", "gnome-screensaver"], stdout=subprocess.PIPE)
        check_pkg = "Setting up gnome-screensaver"
        if check_pkg in install_pkg.communicate()[0]:
            return True

    elif pkg_avil:
        return True

def start_timer(timer):
    while timer:
        print(time.strftime("%Y-%m-%d %H:%M:%S"))
        time.sleep(60)
        timer -= 1
    return 0

def take_break(break_time):
    if verify_pkg():

        print("TAKE A BREAK OF {} minutes".format(break_time))

        #lock the screen
        lock = subprocess.call(["/usr/bin/gnome-screensaver-command", "-l"])
        start_timer(break_time)

        #unlock the screen
        unlock = subprocess.call(["/usr/bin/gnome-screensaver-command", "-d"])

if __name__ == "__main__":

    count = 1
    while True:
        print("20 minute timer started with break {} minutes".format(BREAK1))
        start_timer(TIME)

        #count of 3 will make an hour. i.e 20*3=60 min
        if count == COUNT:
            print("HOUR timer started with break {} minutes".format(BREAK2))
            take_break(BREAK2)
            #intialize the count to 1 after the hourly break
            count = 1
        else:

            take_break(BREAK1)
            count += 1

Any improvements on this code are welcome.


texts:
Here is my attempt on implementing "Degrees of Wikipedia" (much faster version can be seen at degreesofwikipedia.com.It's basically an algorithm which tries to connect two unrelated Wikipedia pages by traversing the internal wikilinks they contain. This version in order to produce faster result doesn't look for the exact match, but just for the matching substring in the url, but that can be changed by editing one line, so it's not really an issue.

import re
from collections import deque

import requests
from bs4 import BeautifulSoup

class UrlNode:
    def __init__(self, url, prev):
        self.url = url
        self.prev = prev
        self.transform_url()

    def transform_url(self):
        if self.url.startswith("/wiki"):
            self.url = "https://en.wikipedia.org" + self.url

    def get_subject(self):
        return self.url.rsplit("/", 1)[1].replace("_", " ")

def is_wiki_url(url):
    url_pattern = r"^/wiki/[a-zA-Z0-9_\,.'-]+$"
    return re.match(url_pattern, url, re.I)

def print_path(result):
    path = []
    distance = 0
    while result is not None:
        path.append(result.get_subject())
        distance += 1
        result = result.prev
    path.reverse()

    print("DISTANCE:", distance)
    print(" -> ".join(path))

def crawl(start, query):
    print(" ==== WIKI CRAWLER === ")
    print("Searching for connnection between '", start, "' and '", query, "'", sep="")
    query = query.replace(" ", "_")
    start = "/wiki/" + start.replace(" ", "_")
    session = requests.session()
    visited_urls = []
    start_url = UrlNode(start, None)
    url_queue = deque()
    url_queue.append(start_url)
    while url_queue:
        url_node = url_queue.popleft()
        if url_node.url in visited_urls:
            continue
        visited_urls.append(url_node.url)
        print(url_node.url)
        req = session.get(url_node.url)
        bs = BeautifulSoup(req.text, 'html.parser')
        for link in bs.find_all('a'):
            if not link.has_attr("href"):
                continue
            if is_wiki_url(link["href"]) and link["href"] not in visited_urls:
                # print("\tFound: ", link["href"])
                new_node = UrlNode(link["href"], url_node)
                if query in new_node.url:
                    print("Total pages visited:", str(len(visited_urls)))
                    return new_node
                url_queue.append(new_node)
    return None

start = "Stack Overflow"
query = "Banana"
result = crawl(start, query)
print_path(result)

This generates result:

Total pages visited: 1054
DISTANCE: 4
Stack Overflow -> Wiki -> University of California -> UC Santa Cruz Banana Slugs

My question is: how can I make this work faster? I welcome both algorithmic suggestions and various "hacks", e.g. requesting the mobile version of the page, which should load faster etc. Here I used breadth-first algorithm, which is very basic and I'm pretty sure better options exist.


texts: Three Cards Trick - Assigning random number to the cards

texts:
At first I have three cards like this:

 ___    ___    ___
|   |  |   |  |   |
| A |  | A |  | Q |
|___|  |___|  |___|

and then I shuffle them to this:

 ___    ___    ___
|   |  |   |  |   |
| 1 |  | 2 |  | 3 |
|___|  |___|  |___|

So now I want to write a function that generates a random number between 1 and 3 and assign it to be the value of the Q card. For example if I generate number 2, the cards when turned around will have this order:

 ___    ___    ___
|   |  |   |  |   |
| A |  | Q |  | A |
|___|  |___|  |___|

So I came up with a code like this

def CreateCard(card):
    print (' _____')
    print ('|     |')
    print ('|  ',card,'  |',sep='')
    print ('|_____|')

def shuffle():
    Q = random.randint(1,4)
    if Q == 1:
        cards = ['Q','A','A']
    elif Q == 2:
        cards = ['A','Q','A']
    else:
        cards = ['A','A','Q']
    return cards
for card in shuffle():
   CreateCard(card)

I guess what I'm asking is this the optimal way since I don't think I'm allowed to use any other function of random module besides randint or randrange.


texts: jQuery toggle buttons to show matching content in sliding panel

texts:
I have a sliding panel that I want to show content in. The content that I want to appear depends on the button that triggers the sliding panel. My project is growing rapidly and I would like to reusable jQuery code or perhaps a plugin. My code works, for example sake I have 6 buttons and 6 hidden divs in side of a sliding panel as shown in the image below:

Upon clicking a button i want to open the sliding panel and show the corresponding content. As of now I have done so by doing this:

Buttons code:

    <button id="p1" data-toggle="slidingPanel"></button>
    <button id="p2" data-toggle="slidingPanel"></button>
    <button id="p3" data-toggle="slidingPanel"></button>
    <button id="p4" data-toggle="slidingPanel"></button>
    <button id="p5" data-toggle="slidingPanel"></button>

Sliding Panel and content divs

jQuery

var slidingPanel = $('#sliding-panel');
$(body).on('click', '[data-toggle="slidingPanel"]', function() {

    //if slider is already open
    if(slidingPanel.hasClass('open')){
        slidingPanel.hide("slide", { direction: "right" }, 500).removeClass('open');
        $('.buttonContent').hide();
        return;
    }
    //if slider is close, open slider
    slidingPanel.show("slide", { direction: "right" }, 500).addClass('open');
    //show content in slider based on button pressed
    $('#' + $(this).attr('id') + 'content').show();
});

Is this the best route. Is there a better way to abstract the code?


texts:
With some effort I've managed to build a very simple (maybe too simple haha) navigation bar for a website.

Is it possible to make a transition on the dropwdown list from height:0 to some suitable height? I've tried and it seems not to be possible. No javascript for now

Any advice or extra tweak I could add? All is greatly welcome!

        /* reset */
        ul {
            list-style: none;
            margin: 0;
            padding: 0;

        }

        /* automatically take height of the elements */
        .main {
            background-color: brown;
            overflow: auto;
            /* automatically adjusts height to anchors */
        }

        .main__lis {
            margin-left: 20px;
            float: left;
            /* float the list items of the main ul */
        }

        a {
            display: block;
            padding: 10px;
            text-decoration: none;
        }

        .dropdown ul {
            width: 120px;
            text-align: left;
            position: absolute;
            background-color: pink;
            display: none;
            box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
        }

        .dropdown:hover ul {
            display: block;
        }
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

Home

News

                Dropdown

link 1

link 2

link 3


texts: Password Generator, generate password of desired length

texts:
While I do know that there are many questions regarding "password generators," I have a different approach and would like to know if it is effective.

1) The below password generator takes on a different approach that other basic password generators, creating an empty string of x length, x being the desired length of the final password, and inserting characters and sub-stringing. I would like to know if this fashion is more effective than adding random characters one-by-one

2) Have I ensured the most random-ness of the characters in the password by using this character set? Or should I rearrange the characters differently?

public static final String CHARACTER_SET = ("aA1bB2cC3dD4eE5fF6gG8hH9iI0jJkKlLmMnNoOpP&qQrRsStT_uUvV-wWxX+yYzZ");

3) I also seek general reminders on java conventions that I do not know.

Here is my full class for reference.

public class PasswordGenerator {

  public static final String VERSION = ("1.0");

  public static final String CHARACTER_SET = ("aA1bB2cC3dD4eE5fF6gG8hH9iI0jJkKlLmMnNoOpP&qQrRsStT_uUvV-wWxX+yYzZ");

  public static void main(String[] args) {
    System.out.println("Welcome to password generator, version: " + VERSION);
    System.out.println(generatePassword(20));
  }

  private static String generatePassword(int passwordLength) {
    String password = "";
    for (int i = 0; i < passwordLength; i++) {
      password = password + " ";
    }
    Random random = new Random();
    for (int i = 0; i < password.length(); i++) {
      if (i == 0) {
        password = String.valueOf(CHARACTER_SET.charAt(random.nextInt(65))) + password.substring(1, password.length());
      } else {
        password = password.substring(0, i) + String.valueOf(CHARACTER_SET.charAt(random.nextInt(65))) + password.substring(i + 1, password.length());
      }
    }
    return password.toString();
  }
}

Note: The 65 comes from the CHARACTER_SET length, which I have found out before.


texts:
When I work a lot with objects, that implements IDisposable I am using this pattern, like shown here with a SqlConnection and a SqlCommand.

    private string _connectionString = "";

    public IEnumerable<User> GetUsers()
    {
        List<User> users = new List<User>();
        string sql = "SELECT * FROM [user]";
        InvokeSql(sql, (connection, command) =>
        {
            IDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                User user = new User();
                users.Add(user);

                user.Name = reader["name"] as string;
            }
        });
        return users;
    }

    private void InvokeSql(string sql, Action<SqlConnection, SqlCommand> action)
    {
        if (string.IsNullOrWhiteSpace(sql))
        {
            throw new ArgumentNullException("sql");
        }

        if (action == null)
        {
            throw new ArgumentNullException("action");
        }

        using (SqlConnection connection = new SqlConnection(_connectionString))
        using (SqlCommand command = new SqlCommand(sql, connection))
        {
            connection.Open();
            action(connection, command);
        }
    }

So I can reuse the InvokeSql and do not have to bother about the disposing.
But is it really a good idea, to use an Action in a using Statement?


texts: React, Redux and SignalR connection dependent on global jQuery

texts:
I'm writing a react/redux application and I'm on a stage when I need to connect it with backend made with .net using a signalR socket connection.

At the moment I've established interconnection between front and backend but I don't quite like how the realization looks like at the moment.

I needed to clearly assign jQuery to the global scope in order ms-signalr-client to see it and use it. I know that I'm able to assign to the global scope using webpack, but in order to do that, I would need to 'eject' create-react-app https://github.com/facebookincubator/create-react-app which is a downside at the moment. I have also tried to use import 'expose-loader?jQuery!jquery'; but once again, webpack loaders doesn't allow to use import syntax this way.
Also, I didn't quite like that in ES6 I need to mix 'imports' with 'require', but that's the only way I found to include 'ms-signalr-client' library after jQuery, so there is no error.

Would appreciate any hints or advice ))

import $ from 'jquery';

window.jQuery = window.$ = $;
require('ms-signalr-client');

const connection = $.hubConnection('http://' + HubURL);
const proxy = connection.createHubProxy('hubName');

function startSignalR(store, cb) {
  proxy.on('broadcastMessage', (message) => {
    console.log(message);
  });

  connection.start(() => {
    console.log('connection started !');
    cb();
  });
}


texts: React Private Routes implementation with adal

texts:
I have integrate aad authentication using react-adal client and secure paths using private routes method
I'm not satisfied with the code structure so I would like to improve it.
Here's the code
index.js
import { runWithAdal } from 'react-adal';
import { authContext } from './auth.js';

const DO_NOT_LOGIN = true;

runWithAdal(authContext, () => {
  console.log("authcontext", authContext)
  // eslint-disable-next-line
  require('./indexApp.js');

}, DO_NOT_LOGIN);

indexApp.js
import React from 'react';
...
import ReactDOM from 'react-dom';
import App from './App';
import {
    BrowserRouter as Router,
    Route,
} from "react-router-dom";
import Welcome from './components/WelcomeComponent/WelcomeComponent'
import PrivateRoute from './components/PrivateRouteComponent/PrivateRouteComponent'

ReactDOM.render(
    <Router>
        <React.StrictMode>
            <ProviderNorth theme={teamsTheme}>
                <Provider store={store}>
                    <PrivateRoute exact path="/" component={App}></PrivateRoute>
                    <Route exact path="/welcome" component={Welcome}>
                    </Route>
                </Provider>
            </ProviderNorth>
        </React.StrictMode>
    </Router>,
    document.getElementById('root')
);
serviceWorker.unregister();

First as I'm making logging via a button is there a way to get rid of indexApp ? I tried to eliminate it but when I login, the welcomepath does not redirect to / anymore and stays in /welcome.
Welcome.js
Here I check if user is loggedin first then redirect to / or not
...
import { authContext } from '../../auth'

import {
    Redirect,
} from "react-router-dom";
import React from 'react';

function Welcome(props) {
    const isLogged = authContext.getCachedUser();
    return (
        isLogged === null ? (
            <div>
                <Header as="h1" content="Welcome to Heedify Reports Page" />
                <Header as="h2" content="Login" />
                <Flex gap="gap.smaller">
                    <Button content="Login" primary onClick={() => {
                        authContext.login().then(data => {
                            console.log("log in", data)
                        })
                    }} />
                </Flex>
            </div>) : <Redirect
                to={{
                    pathname: "/"
                }}
            />
    )
}

export default Welcome

PrivateRoute
import React from 'react';
import {
Redirect,
Route,
} from "react-router-dom";
import { authContext } from '../../auth';
const PrivateRoute = ({ component: Component, ...rest }) => {
    return (
        <Route
            {...rest}
            render={props => {
                return authContext.getCachedUser() !== null ? (
                    <Component {...props} />
                ) : (
                        <Redirect
                            to={{
                                pathname: "/welcome"
                            }}
                        />
                    )
            }}></Route>)
}

export default PrivateRoute