texts: Queue that connects multiple producers and multiple consumers

texts:
The scenario is about processing 'Message' objects. Producer creates them and Consumer does the consumption.

class Message{...}

class MessageBatch{

    public MessageBatch(Collection<Message> messages){...}

    public List<Message> getMessages(){...};

    //more utility methods like getMessageIds(), etc.
}

The following is a pipeline object (queue) that connects multiple producer threads and multiple consumer threads. Both my producers & consumers are I/O bound (database) and that justifies this attempt.

API requirements

[A] Ability to add & get batch of Message objects.
[B] Consumer has a way to realize that no more elements are expected.

public class MessagePipeline {

    //[1]; to support API requirement [B]
    public static final MessageBatch SENTINEL_BATCH = new MessageBatch(Collections.<Message>emptyList());

    private BlockingQueue<Message> messageQueue = new LinkedBlockingQueue<>();

    // to support API requirement [B]
    private CountDownLatch producersWorkCompletionLatch;

    public MessagePipeline(int numOfProducerThreads) {
        this.producersWorkCompletionLatch = new CountDownLatch(numOfProducerThreads);
    }

    public boolean add(MessageBatch batch) {
        isWriteAllowed(); // UPDATE: this step is misleading and thinking of removing this.
        return messageQueue.addAll(batch.getMessages());
    }

    // returns a batch containing up to maxSize elements.
    public MessageBatch takeBatch(int maxSize) {
        List<Message> messages = drainIfMoreElementsExpected(new ArrayList<Message>(), maxSize);

        return messages.isEmpty() ? SENTINEL_BATCH : new MessageBatch(messages);
    }

    //[2]: Producer should invoke this at the end.
    public void notifyCompletion() {
        producersWorkCompletionLatch.countDown();
    }

    public boolean isMoreElementsExpected() {
        boolean isExpected = !(producersWorkCompletionLatch.getCount() == 0 && messageQueue.size() == 0);
        return isExpected;
    }
    //[3] : This is CPU bound waiting. TODO: Make it I/O bound.
    private List<Message> drainIfMoreElementsExpected(List<Message> messages, int maxSize) {
        while (messages.isEmpty() && isMoreElementsExpected()) {
            messageQueue.drainTo(messages, maxSize);
        }
        return messages;
    }

    /**
     * Assures write-operations 'happen-before' producer-threads-completion.
     */
    private void isWriteAllowed(){
        if(producersWorkCompletionLatch.getCount() == 0){
            throw new UnsupportedOperationException("New elements are not accepted after all producer threads notify of completion");
        }
    }
}

Questions

I'm looking forward to code review in general.
Do approaches [1] and [2] seem right?
[3]: Am I right that it is CPU bound? How do I make it I/O bound waiting? Introducing locks seem to make it more complicated.

I'm in the middle of writing unit tests. It's good to know if I missed anything because unit-testing multi-threaded code tells you that the code is broken only one in million times and doesn't tell you why!


texts:
This is my code for a very basic video game I created today. I did not create this to be a fun game to play. I created this to test my skills on conditional coding, etc. Please critique this.

// Created by Andrew Tew
// My Test Studio

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

int main ()
{
string yay;
string actyay = "yes";
string nactyay = "no";
string EastEgg = "maybe";
string replay = "replay";
bool Chest_Unlocked;
bool Have_Knife;
bool Dead = !true;
Start:
system ("cls");
cout << "Do you pick up the knife?\n";
cin >> yay;
if (yay == actyay){
    Have_Knife = true;
}if (yay == nactyay){
    Have_Knife = false;
}if (yay == EastEgg){
    goto EasterEgg;
}

system ("cls");

cout << "Did you unlock the chest?\n";
cin >> yay;
if (yay == actyay){
    Chest_Unlocked = true;
}if (yay == nactyay){
    Chest_Unlocked = false;
}
if (Chest_Unlocked == true){
    system ("cls");
    cout << "Inside the chest is a big fat snake :O\n";
    system ("pause");
}else {

    system ("cls");
    cout << "You Lose\n";
    Dead = true;
    goto DEAD;
    system ("pause");
}
if (Have_Knife == true){
    system ("cls");
    cout << "Since you have dat handy knife you kill dat snakey\n";
    system ("pause");
}else{
    system ("cls");
    cout << "YOU DIE HAHAHAHAHAHAHA\n";
    Dead = true;
    goto DEAD;
    system ("pause");
}
if (Dead == false){
    goto EasterEgg;
}else goto DEAD;
DEAD:
if (Dead == true){
    cout << "You arise to heaven and meet God the Almighty\n";
    cout << "God says unto you...\n";
    cout << "     Thou hast lost the game of life and death";
    cout << "because of this you have come back unto my realm.";
    cout << "I give you a choice that will only come once in a lifetime.\n";
    cout << "Would you like to replay dat crappy little game or have\n";
    cout << "Fun in Heaven?\n";
    cin >> yay;
    if (yay == replay){
        goto Start;
}else {
    goto EasterEgg;
    }}

EasterEgg:
system ("cls");
cout << "You Win!";

system ("pause");
return 0;
}


texts:
John has discovered various rocks. Each rock is composed of various
  elements, and each element is represented by a lowercase Latin letter
  from 'a' to 'z'. An element can be present multiple times in a rock.
  An element is called a 'gem-element' if it occurs at least once in
  each of the rocks.

  Given the list of rocks with their compositions, you have to print how
  many different kinds of gems-elements he has.

  Input Format

  The first line consists of N, the number of rocks. Each of the next N
  lines contain rocks’ composition. Each composition consists of small
  alphabets of English language.

  Output Format

  Print the number of different kinds of gem-elements he has.

  Constraints

  \$1 ≤ N ≤ 100\$

  Each composition consists of only small Latin letters ('a'-'z'). 1 ≤ Length of each composition ≤ 100

  Sample Input

3
abcdde
baccd
eeabg

  Sample Output

2

  Explanation

  Only "a", "b" are the two kind of gem-elements, since
  these characters occur in each of the rocks’ composition.

I tried to solve this HackerRank problem in Java. Do you see any areas for improvement?

public int getGems(List<String> list) {

    if (list != null && !(list.size() > 0)) {
        throw new IllegalArgumentException("Invalid Input");
    }

    int gemsCount = 0;
    int s = list.size();
    int cnt = 1;

    // assume list(0) will always have gems
    String str = list.get(0);
    char[] ch = str.toCharArray();
    for (char c : ch) {
        for (int i = 1; i < s; i++) {
            String st = list.get(i);
            if (st.indexOf(c) > -1) {
                cnt++;
                continue;
            } else {
                cnt = 1;
                break;
            }
        }
        if (cnt == s) {
            gemsCount++;
            cnt = 1;
        }
    }
    return gemsCount;
}


texts:
I have several calculus to do in my ruby app.
My code is currently working but I find it very ugly.

@guestreviews = GuestReview.where(:reviewed_id => @user.id)
@hostreviews = HostReview.where(:reviewed_id => @user.id)
@hospitalityrate = 0
@foodrate = 0
@placerate = 0
@hostreviews.try(:each) do | rate |
  @hospitalityrate += rate.people_rate
  @foodrate += rate.food_rate
  @placerate += rate.place_rate
end
@hospitalityrate = (@hospitalityrate / @hostreviews.size).round
@foodrate = (@foodrate / @hostreviews.size).round
@placerate = (@placerate / @hostreviews.size).round
@averagerate = ((@hospitalityrate + @foodrate + @placerate) / @hostreviews.size).round

Any idea how to make it still readable but less ugly ?


texts: Remove unwanted characters from specified column in all Worksheets

texts:
I need to remove some unwanted characters from a given column in all Worksheets from my Workbook. The code below works perfectly, but I'd like to know if there is a better/cleaner/faster way of doing this.

What exactly am I doing?
I am storing all unwanted/forbidden characters in an Array, after that I'm walking through all worksheets and replacing those characters with ""(empty) in each cell in column "J". In this case it will Always be in column J, but for maintainability (in case the template changes in future), I'm declaring it as a constant.

Why do I need to do this?
The data in this Workbook is uploaded to ALM, which does not allow any of those characters in the "Test Subject" field, hence I'm removing them. I chose this approach because I think it is easier, but if you have a better way of doing this (e.g. preventing the user from typing them in the first place, or any other approach that doesn't even require coding) it will be very welcome.

Code:

Sub replaceAll()

    Const FIRST_ROW As Integer = 2, TEST_COLUMN As String = "J"
    Dim arrForbidden() As String: arrForbidden = Split("\,/,:,%,',*,?,<,>,|,"",.", ",")

    Dim ws As Worksheet
    Dim lastRow As Long
    Dim rngCells As Range
    Dim cell, character

    For Each ws In ThisWorkbook.Worksheets

        lastRow = ws.Cells(ws.Rows.Count, TEST_COLUMN).End(xlUp).Row
        Set rngCells = ws.Range(TEST_COLUMN & FIRST_ROW).Resize(lastRow - FIRST_ROW + 1, 1)

        For Each cell In rngCells
            For Each character In arrForbidden
                cell.Value = Replace(cell.Value, character, "")
            Next
        Next
    Next

End Sub


texts: Filtering out employees that do not meet some criteria, using list comprehensions

texts:
Right now I have a list of dictionaries. In order to filter out all the entries I do not want included in the list, I am running it through multiple list comprehensions.

Is there a more Pythonic or better way to write these comprehensions that seem repetitive?

#FILTER OUT ALL EMPLOYEES WHO WILL NOT BE FACTORED INTO METRICS
inScope = [s for s in set2 if s['LEAD_TIME'] >= 0]#lead times 0 or more
set2 = inScope

inScope = [s for s in set2 if s['WRK_RLTN_DSC'] != "INDEPENDENT CONTRACTOR"]#not independent contractor
set2 = inScope

inScope = [s for s in set2 if s['WRK_RLTN_DSC'] != "OUTSIDE CONSULTANT"]#not outside consultant
set2 = inScope

inScope = [s for s in set2 if s['WRK_RLTN_DSC'] != "OUTSIDE CONTRACTOR"]#not outside contractor
set2 = inScope

inScope = [s for s in set2 if s['WRK_RLTN_DSC'] != "EMP OF STRATEGIC INVESTMENT CO"]#not emp of strategic investment co
set2 = inScope

inScope = [s for s in set2 if s['BUS_GRP_CD'] != "FIL"]#In scope after removal of FIL Int'l Associates
set2 = inScope


texts:
I have a class which will add or edit a child. So whenever I click on "save," I need to check the child image. If it's an image, then I need to upload to the image server. Once that's done only, I need to save all other data to the data server. Here, I am looking for better names for methods save() and updateChild().

 func saveAction() {
      switch validationResult {
      case .Success:
         save()
      case .Failure(let errorType):
         displayErrorAlert(errorType)
      }
 }

func save() {
    let child = addChildView.tableView.datasource
    if let image = child.image {
        uploadImage(image)
    } else {
        self.updateChild()
    }
}

func uploadImage(image: UIImage) {
    UploadManager.uploadImage(image, completion: { (response) in
        switch response {
        case .success:
            self.updateChild()
        case .error:
            self.updateChild()
        }
    })
}

func updateChild() {
    if addChildType == .new {
        addChild()
    } else {
        editChild()
    }
}


texts: Critique My Codeigniter Custom CMS Pages Model

texts:
I am currently developing a custom CMS being built on top of Codeigniter and was wondering if you can spot any flaws in my page fetching model code. The page fetching model is not entirely complete but the main functionality for retrieving a page is done, as well as retrieving modules assigned to a page (a module is really just a widget).

Can this model be better in some parts, perhaps in relation to the joins I am doing? although not really joins, but multiple queries to pull out bits of related info the pages like modules and media.

<?php

  class Mpages extends CI_Model {

      public function __construct()
      {
          parent::__construct();
      }

      public function fetch_page($page_slug = 'home')
      {
          $db = $this->db;

          $query =
            $db
               ->where('page_status', 1)
               ->where('page_slug', strtolower($page_slug))
               ->get('pages')
               ->result_array();

          $page_id = $query[0]['id'];

          $query['modules'] =
            $db
                ->select('modules.module_name, modules.module_slug, modules.id moduleid')
                ->where('page_id', $page_id)
                ->join('pages_modules lpm', 'moduleid = lpm.module_id')
                ->order_by('module_order', 'asc')
                ->get('modules')
                ->result_array();

          /*$query['media'] =
            $db
                ->select('lucifer_media.media_file_name, lucifer_media.media_file_extension, lucifer_media.media_directory')
                ->join('lucifer_pages_media', 'lucifer_pages_media.page_id = '.$page_id.'')
                ->get('lucifer_media')
                ->result_array();*/

          if ($query) {

            return $query;

          } else {
            return false;
          }
      }

      public function fetch_navigation()
      {
        $result = $this->db->order_by("nav_order", "asc")->where('published', 1)->get('navigation')->result_array();
        return $result;
      }

      public function fetch_layout($id)
      {

          $result = $this->db->where('id', $id)->get('layouts')->result_array();

          return $result[0];

      }

  }

?>


texts: Mapping Many Parameters Programmatically

texts:
I have a function for merging data from an object (a PrintTestDataItem) into a template file for a printed label (a LabelFormatDocument called label in this snippet). The LabelFormatDocument is a third-party class that I use to set various fields on my label and I do this by setting the numerous substrings to the values that I want from my PrintTestDataItem object.

There are a lot of these substrings and my current function just sets each substring sequentially, which is obviously not an ideal way to do this sort of operation. What would be a better way to set these substrings programmatically and any other suggestions for increasing the maintainability of this function?

My first idea is to use a dictionary to store the substring names and map them to the appropriate parameter of the PrintTestDataItem, is this the right path to go down?

public void MergePrintData(PrintTestDataItem printTestData)
{
    label.SubStrings["Barcode"].Value = printTestData.IDNumber.ToString();
    label.SubStrings["Date"].Value = printTestData.TestDate.ToString();
    label.SubStrings["WRN"].Value = printTestData.WRNNumber;
    label.SubStrings["Operator"].Value = printTestData.OperatorName;
    label.SubStrings["PrintheadType"].Value = printTestData.HeadType;
    label.SubStrings["PrintheadSerial"].Value = printTestData.HeadSerial;
    label.SubStrings["Batch"].Value = printTestData.BatchNumber;
    label.SubStrings["PrintFrequency"].Value = (printTestData.PrintFrequency + "kHz");
    label.SubStrings["PrintDistance"].Value = (printTestData.PrintDistance + "mm");
    label.SubStrings["InkType"].Value = printTestData.InkType.ToString();
    label.SubStrings["InkColour"].Value = printTestData.InkColour;
    label.SubStrings["InkTemperature"].Value = (printTestData.InkTemperature + "°C");
    label.SubStrings["DifferentialPressure"].Value = (printTestData.DifferentialPressure + "mBar");
    label.SubStrings["MeniscusPressure"].Value = (printTestData.MeniscusPressure + "mBar");
    label.SubStrings["Comments"].Value = printTestData.Comments;
    label.SubStrings["EncoderDivide"].Value = printTestData.EncoderDivide;
    label.SubStrings["EncoderMultiply"].Value = printTestData.EncoderMultiply;
    label.SubStrings["Offset"].Value = printTestData.Offset;
    label.SubStrings["NumberOfGreyLevels"].Value = printTestData.NumberOfGreyLevels;
    label.SubStrings["Mirror"].Value = BooleanRemapping(printTestData.Mirror);
    label.SubStrings["DIR"].Value = BooleanRemapping(printTestData.DIR);
    label.SubStrings["ReversePrint"].Value = BooleanRemapping(printTestData.ReversePrint);
    label.SubStrings["PrintDirection"].Value = printTestData.PrintDirection.ToString();
    label.SubStrings["PrintMode"].Value = printTestData.PrintMode.ToString();
    label.SubStrings["PrintTransportMode"].Value = printTestData.PrintTransportMode.ToString();
    label.SubStrings["AmbientTemperature"].Value = (printTestData.AmbientTemperature + "°C");
    label.SubStrings["HoursRun"].Value = printTestData.HoursRun;
    label.SubStrings["LinesDown"].Value = printTestData.LinesDown;
}


texts: how to optimize vba looping code using variables?

texts:
This looping has no problem if I have under 100 rows in the looping table sheet. However, If it go over 100 rows, looping takes a while to filtering and paste value in looping sheet. Is there any way to optimize this VBA code to run faster?

Sub Testingloop()
Dim endrown As String
Dim ex As String
Dim ez As String
Dim eh As String
Dim eg As String
Dim el As String
Dim ee As String
Dim es As String
Dim ef As String
Dim ei As String
Dim i As Integer
Dim LastRowColumnA As Long: LastRowColumnA = Sheets("looping").Cells(Rows.Count, 1).End(xlUp).Row

Application.ScreenUpdating = False

Sheets("looping table").Select
endrown = Sheets("looping table").Range("I1000").End(xlUp).Row
    For i = 3 To endrown

        ee= Cells(i, 9).Value
        ex= Cells(i, 10).Value
        ez= Cells(i, 11).Value
        es = Cells(i, 12).Value
        ef = Cells(i, 13).Value
        ei = Cells(i, 14).Value
         eh = Cells(i, 15).Value
        eg= Cells(i, 16)
        el= Cells(i, 17)

        Sheets("looping").Select
             ActiveSheet.UsedRange.AutoFilter Field:=1, Criteria1:=ee
             ActiveSheet.UsedRange.AutoFilter Field:=2, Criteria1:=ex
             ActiveSheet.UsedRange.AutoFilter Field:=3, Criteria1:=ez
            ActiveSheet.UsedRange.AutoFilter Field:=4, Criteria1:=es
            ActiveSheet.UsedRange.AutoFilter Field:=5, Criteria1:=ef
             ActiveSheet.UsedRange.AutoFilter Field:=6, Criteria1:=ei
            ActiveSheet.UsedRange.AutoFilter Field:=7, Criteria1:=eh
        On Error Resume Next
        Range("H2:H" & LastRowColumnA).SpecialCells(xlCellTypeVisible).Value = eg
        Range("I2:I" & LastRowColumnA).SpecialCells(xlCellTypeVisible).Value = el
            ActiveSheet.ShowAllData
                Sheets("looping table").Select

                   Next i

End Sub


texts: Quick select the kth smallest value (part 2)

texts:
Here is my code for quick select and a continued discussion from (Quick select the kth smallest value). Since it is new code, I made a new post.

Any performance improvement in terms of algorithm time complexity, code bugs or code style are appreciated.

More specific questions are:

I am using i <= j, like while i <= j, and while i <= j and numbers[i] <= pivot. Is there a way to make it i<j to have a fewer number of comparisons without bugs?
Is it safe to write code as numbers[j] > pivot, or should I write it as i<=j and numbers[j] > pivot?

import random
def quick_select(numbers, start, end, k):
    '''
    :param numbers: input unsorted number
    :param start: inclusive start bound
    :param end: inclusive end bound
    :param k: kth element, index from zero
    :return: return kth element
    '''
    if not numbers:
        return None
    if start == end:
        if k == start:
            return numbers[start]
        else:
            raise Exception('invalid input! ')
    pivot = numbers[end]
    i = start
    j = end - 1
    while i <= j:
        while i <= j and numbers[i] <= pivot:
            i += 1
        while numbers[j] > pivot:
            j -= 1
        if i < j:
            numbers[i], numbers[j] = numbers[j], numbers[i]
    numbers[end], numbers[i] = numbers[i], numbers[end]
    if i == k:
        return numbers[i]
    elif i > k:
        return quick_select(numbers, start, i-1, k)
    else:
        return quick_select(numbers, i+1, end, k)
if __name__ == "__main__":
    numbers = [1,2,3]
    print quick_select(numbers, 0, len(numbers)-1, 0)
    print quick_select(numbers, 0, len(numbers) - 1, 1)
    print quick_select(numbers, 0, len(numbers) - 1, 2)
    print '============'
    numbers = []
    for i in range(10):
        numbers.append(random.randint(0,10))
    k = random.randint(0,9)
    print 'numbers, ', numbers, 'k, ', k, 'result, ', quick_select(numbers, 0, len(numbers)-1, k)
    print sorted(numbers)


texts:
I wrote a Angular filter to use filters based on properties that handles some specific properties differently.

Is there a way to improve or use some built-in Angular filter to avoid extra code?

Usage:

<div ng-repeat="item in items | myObjectFilter: { someProp: user.uid, pending: true }">

Code:

angular.module('app', []).filter('myObjectFilter', function () {
    function _filter(source, search) {
        if (!source) { return source; }

        var result = [], defaultFilters;

        //default filter setting
        defaultFilters = {
            pending: false,
            refusedAt: null
        };

        search = angular.extend({}, defaultFilters, search);

        angular.forEach(source, function (value, key) {
            var isFiltered = true;

            for (var x in search) {
                if (value.hasOwnProperty(x)) {
                    var isEqual = false;

                    // handle specific properties or simply compare
                    switch (x) {
                        case 'someProp':
                        case 'someProp2':
                            isEqual = value[x].uid == search[x];
                            break;
                        default:
                            isEqual = value[x] == search[x];
                            break;
                    };

                    isFiltered = isFiltered && isEqual;

                    if (!isEqual) {
                        break; //exit loop if filter not passed
                    }
                }
            }

            if (isFiltered) {
                result.push(value); // add item to filterd result
            }
        });

        return result;
    };

    return _filter;
});


texts:
I have built RESTful web services. The services endpoints have a similar logic:

If the input validation succeeds, do a database operation and return the result.
If the db operation fails, return the db error.
If the validation fails, return a response with information on the failed validation.

My code was explicit in the sense you can read the code and understand the flow of the program. A coworker refactored it so that this basic flow is refactored in a utility class which main function takes the request body, the db operation and the handlers. Now the code doesn't express the flow but the basic logic is refactored.

Which code better follows best practice? Would you sacrifice readability for refactoring? Yes, the unit test will be reduced a bit too.

Example:

Before:

save: function (req, res, next) {
 var dao = topicsDaoFactory.create(req.dbSession);

 validate(req.body.topic, constraintsObj,
   function success () {
     dao.save(req.body.topic, function saveHandler (err, result) {
       if (err) {
         res.error(err);
       } else {
         res.send(result);
       }
     });
   },
   function error (errors) {
     res.fail(errors);
   });
}

After:

save: function (req, res) {
  var dao = topicsDaoFactory.create(req.dbSession);

  ControllerUtils.validateAndTryOperation(req, res, {
    input: req.body.topic,
    constraints: constraintsObj,
    operation: function (input, callback) {
      dao.create(Topic.createFromScratch(input), callback);
    }
  });
}


texts:
Related to, but not exactly a follow up of this question. After fixing some issues discovered in the last review, I added a little more functionality to the Enumerable class. The problem is, I've never sorted before. I tried (and failed)to implement a few of the standard algorithms before coming up with this. It's not very efficient. It has to check to see if the collection IsSorted and just keeps looping until it is.

Is there a way to make this more efficient without using a more advanced algorithm?
What would be a simple to understand algorithm that is more efficient than this?

I realize that I could simplify some logic if I created some interfaces, but I would like to work with "built in" collections without wrapping everything in a class that implements an interface.

Bonus points to anyone who can tell me what algorithm I ended up using. I just kept testing until it worked.

Public Function Sort(collectionObject As Collection) As Collection

    Dim item As Variant
    Dim innerItem As Variant

    Dim i As Long
    Dim j As Long
    Dim index As Long

    Do Until IsSorted(collectionObject)
        For i = 1 To collectionObject.Count
            index = i

            If IsObject(collectionObject(i)) Then
                Set item = collectionObject(i)
            Else
                item = collectionObject(i)
            End If

            For j = i To collectionObject.Count
                If IsObject(collectionObject(j)) Then
                    Set innerItem = collectionObject(j)
                Else
                    innerItem = collectionObject(j)
                End If

                If item > innerItem Then
                    collectionObject.Add item, After:=j
                    collectionObject.Remove index
                    index = j
                End If
            Next j
        Next i
    Loop
End Function

Private Function IsSorted(collectionObject As Collection) As Boolean

    Dim item As Variant
    Dim previous As Variant

    For Each item In collectionObject
        If item < previous Then
            IsSorted = False
            Exit Function
        End If

        If IsObject(item) Then
            Set previous = item
        Else
            previous = item
        End If
    Next item

    IsSorted = True
End Function


texts:
This is the follow-up question for A recursive_transform Function For Various Type Nested Iterable With std::variant Implementation in C++. As G. Sliepen's answer mentioned, leaving only recursively transforming operation for recursive_transform() may be a better idea. As the result, the implementation of recursive_transform function is kept in the following form. Moreover, the forward declarations have been removed.
template<class T, class _Fn> requires is_iterable<T>
static inline T recursive_transform(const T input, _Fn func)
{
    T returnObject = input;

    std::transform(input.begin(), input.end(), returnObject.begin(), func);
    return returnObject;
}

template<class T, class _Fn> requires is_iterable<T> && is_element_iterable<T>
static inline T recursive_transform(const T input, _Fn func)
{
    T returnObject = input;
    std::transform(input.begin(), input.end(), returnObject.begin(),
        [func](const auto& element)
        {
            return recursive_transform(element, func);
        }
    );
    return returnObject;
}

However, I still want to handle the compound structure with ranges and std::variant, such as std::vector<std::variant<double>>. A new function get_from_variant comes up in my mind in order to focus on the operations with these things.
template<typename T_variant, typename T>
static inline auto get_from_variant(T_variant input_variant)
{
    T return_val;
    std::visit([&](auto&& arg)
        {
            return_val = static_cast<T>(arg);
            return arg;
        },
        input_variant);
    return return_val;
}

The tests of this get_from_variant function:
int main()
{
    //  get_from_variant function test
    std::variant<double> testNumber = 1;
    std::cout << get_from_variant<decltype(testNumber), double>(testNumber);

    //  The usage of recursive_transform function and get_from_variant function
    std::variant<double> variant_number = 3.14;

    std::vector<decltype(variant_number)> testVector1;
    testVector1.push_back(variant_number);
    testVector1.push_back(variant_number);
    testVector1.push_back(variant_number);
    std::cout << get_from_variant<std::variant<double>, double>(recursive_transform(testVector1, [](auto x){ return get_from_variant<std::variant<double>, double>(x) + 1; }).at(0)) << std::endl;

    return 0;
}

All suggestions are welcome.

Which question it is a follow-up to?
A recursive_transform Function For Various Type Nested Iterable With std::variant Implementation in C++

What changes has been made in the code since last question?
In order to handle the compound structure with ranges and std::variant, such as std::vector<std::variant<double>> in a better way, a new function get_from_variant has been created.

Why a new review is being asked for?
In my opinion, I am not sure whether the design of the function get_from_variant is good? Is the idea or the usage good or not? Any comment is welcome.


texts: Build script for an operating system written in C++


texts: Using as few queries as possible for many table associations

texts:
I have a table containing about 30k rows of data and there's several table associations. The problem is that there's like 18 columns, and each column requires 1 db query.

Here's an example of what I'm doing:

if col_num == 0
    tmp_string_text = finding_phase
elsif col_num == 1
    tmp_string_text = ""
elsif col_num == 2
    tmp_string_text = ""
elsif col_num == 3
    tmp_string_text =  finding.vuln_finding.severity
elsif col_num == 4
    tmp_string_text = finding.node.ip
elsif col_num == 5
    tmp_string_text =  finding.node.host_name
elsif col_num == 6
    tmp_string_text =  finding.node.dns_name
elsif col_num == 7
    tmp_string_text = finding.port
elsif col_num == 8
    tmp_string_text =  finding.pentest_finding.name
elsif col_num == 9
    tmp_string_text =  finding.vuln_finding.name
elsif col_num == 10
    tmp_string_text = finding.vuln_finding.description
elsif col_num == 11
    tmp_string_text = finding.vuln_finding.solution
elsif col_num == 12
    tmp_string_text = finding.additional_output
elsif col_num == 13
    tmp_string_text = finding.cve
elsif col_num == 14
    tmp_string_text = finding.node.os
elsif col_num == 15
    tmp_string_text =  finding.node.device_type
elsif col_num == 16
    tmp_string_text =  finding.node.scan_time
end

As a result, there's going to be 15 queries to the DB per 1 row. Is there any way that I can make this more efficient? This takes a REALLY long time when I have 30k rows. Not looking for anyone to flame here, just looking for advice. Pretty new to Ruby on Rails but learning as I go.

Basically, "finding" in this case is a result of @my_report.findings and it's going through each finding and pulling back data.


texts: Random alphanumeric string generator function (C, Windows, bcrypt.h)

texts:
The function uses the Windows "Cryptography API: Next Generation" (bcrypt.h)'s BCryptGenRandom function to generate random bytes - one for each character.
It returns the number of characters (excluding NUL-terminator) written to the buffer, -1 in the case of a bad argument, or -2 in the case of an error.
Example usage of the function:
wchar_t str[9]; // 8 chars + NUL
rand_alphanum_str(str, sizeof (str));
printf("8 random alphanumeric characters: %wS\n", str);

Function code:
int rand_alphanum_str(WCHAR *buffer, size_t buffer_size) {
    if(!buffer || buffer_size < 2) { return -1; }

    int chars = buffer_size / sizeof (WCHAR) - 1; // -1 for null terminator

    // need one random byte per character to be generated
    unsigned char *rand_bytes = malloc(chars);
    if(!rand_bytes) { return -2; }

    // filling rand_bytes buffer
    if(!NT_SUCCESS(BCryptGenRandom(NULL, rand_bytes, chars,
                                   BCRYPT_USE_SYSTEM_PREFERRED_RNG))) {
        free(rand_bytes);
        return -2;
    }

    for(int i = 0; i < chars; ++i) {
        // rand_bytes[i] is in range [0, 255].
        // need a number in range [0, 61] - as there are 62 alphanumeric
        // characters

        // bit-twiddling to attempt to maintain a uniform distribution:

        // discard 2 least-significant bits - rand_bytes is now in [0, 63]
        rand_bytes[i] >>= 2;
        if((rand_bytes[i] >> 5) & 1U) {   // if the now most-significant bit is set,
            rand_bytes[i] &= ~(1UL << 1); // clear the 2nd least-significant bit
            // (only cleared if most-significant bit is set so as to avoid
            // throwing distribution off by having a bit which is never set)
        }
        // rand_bytes[i] is now in [0, 61]

        // of the 62 possible values of rand_bytes[i]:
        //   - [0, 9] represent numeric digits
        //   - [10, 35] represent uppercase letters
        //   - [36, 61] represent lowercase letters
        // the offset of rand_bytes[i] from the low end of the range it lies in
        // is added to said range's first ASCII value to give a random character
        // in that range
        if(rand_bytes[i] <= 9) {
            buffer[i] = L'0' + rand_bytes[i];
        } else if(rand_bytes[i] <= 35) {
            // -10 for offset from beginning of numeral range
            buffer[i] = L'A' + rand_bytes[i] - 10;
        } else {
            // -36 for offset from beginning of uppercase range
            buffer[i] = L'a' + rand_bytes[i] - 36;
        }
    }
    buffer[chars] = L'\0';

    free(rand_bytes);
    return chars;
}

Thank you!


texts:
I'm creating Sudoku in JS but can't find the way to extract the numbers from the squares. The numbers from the rows and columns are easy to extract but I can't find the way around the squares. According to users input, I'll validate the column, then the row and finally the squares to see if the numbers are being repeated. Is this best practice?

Globals:

 var numIni = 9; //Number of squares per side;
 var squared = Math.sqrt(numIni); // I'll need this.

Column check:

function getColumn(){
var num = 30; //USER's INPUT
var colNums = []; //numbers IN the column
var countCol = num; // column anchor
while(countCol > numIni ){
    countCol -= numIni
}
colNums[0] = countCol;

for(i=1;i< numIni;i++){
    colNums[i]= colNums[i-1]+9;
 }
}

Row check:

function getRow(){
var num = 50; //USER's INPUT
var rowAnchor = (Math.ceil(num/numIni))*numIni-(numIni-1);

var rowNums=[rowAnchor]//numbers IN the row

for(i=1;i< numIni;i++){
    rowNums[i]= rowAnchor+i;
}

}

These last two work, but the squares are killing me. I'm first extracting the anchors, then building the squares and validating the number against that. It's getting quite long. Is there a better way to write this? Is the logic inefficient? If it's right, I'm stuck anyway.

Squares check (so far):

function getSquare(){
var boxes = [];
var boxesAnchor = [];
boxes[0]=1;
boxesAnchor[0]=1;

for(i=0; i< numIni*numIni ; i++){
    boxes[i]= squared + ((i-1)* squared )+1;
    }

for(i=0; i< numIni*squared ; i++){
   for(j=0; j< squared ; j++){
      boxesAnchor[i] = boxes[i];
      boxesAnchor[i+j] = boxes[i+j];
      boxesAnchor[i+j] = boxes[i+j];
   }
  i +=(numIni-1);
}

boxesAnchor.clean(undefined);// method added to the Array object

}


texts: Find whether a given number is a perfect square or not

texts:
I am trying to find whether a given number is a perfect square or not by using just addition and subtraction.

Please review my code.

#include<stdio.h>
int check(int);
main()
{
    int N;

    printf("\n Enter the N:");
    scanf("%d",&N);
    if(check(N))
    {
        printf("\n[%d] Perfect Square:\n",N);

    }

    else
    {

        printf("\nNot perfect Square\n");

    }
}
int check(int n)
{
    int i=1;

    while(n>0)
    {
        n-=i;
        printf("[%d]",n);
        i+=2;
    }
    if(n==0)
        return 1;

    return 0;

}


texts: Limiting the amount of Calls to a Server

texts:
I have a server side operation which takes a percentage value from 0 - 100. The user controls this percentage using a SeekBar on the android client.

Time-wise the operation is expensive, so I don't want to send commands faster than the server can update. To limit the amount of actions sent, I have limited the client it to 10 calls per second by doing the following:

public class ControlPanel extends Activity {
    private SeekBar seekbar;

    private Thread updateServerThread;
    private final Runnable updateServerRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                updateServer(seekbar.getProgress());
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.control_panel);

        seekbar = (SeekBar) findViewById(R.id.my_seekbar);

        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) {
                if (updateServerThread == null || !updateServerThread.isAlive()) {
                    updateServerThread = new Thread(updateServerRunnable);
                    updateServerThread.start();
                }
            }
            @Override public void onStartTrackingTouch(SeekBar seekbar) { }
            @Override public void onStopTrackingTouch(SeekBar seekbar) { }
        });
    }
    ...


texts:
Is there a better way to have a minimal Python plugin mechanism than the following?

(This was inspired from this post.)

import sys
import pkgutil
import os.path
import plugins
pluginsPath = os.path.dirname(plugins.__file__)
pluginModules = [name for _, name, _ in pkgutil.iter_modules([pluginsPath])]
dictOfPlugins = {}
for plugin in pluginModules:
    thePluginModuleName = "plugins."+plugin
    result = __import__(thePluginModuleName)
    dictOfPlugins[plugin] = sys.modules[thePluginModuleName]

(This does assume that all your plugins are in a directory called "plugins" and thus are modules in that package, and that that directory has a blank __init__.py file in it.)

If you wanted to look for a particular plugin, the name would be a key in the dictOfPlugins, and the module object itself would be the value. Assuming you knew what the interface to your Python plugin modules would be, this would seem to do the job. Is there a better way to do this?


texts:
I'm trying to make a scala interface to the spotify API. I'm using it to learn Scala. I come from mostly a python background.

import dispatch._, Defaults._

trait Request {
  val name: String
  val endpoint: String
}

case class Track(name: String) extends Request {
  override val endpoint = "track.json"
}

case class Album(name: String) extends Request {
  override val endpoint = "album.json"
}

case class Artist(name: String) extends Request {
  override val endpoint = "artist.json"
}

object Spotify {

  def getResponse(req: Request) = {
    val params = Map("q" -> req.name)
    val spotifyUrl = host("ws.spotify.com")

    spotifyUrl / "search"/ "1" / req.endpoint <<? params

  }

  val foo = Album("foo")
  val songs = Http(getResponse(foo) OK as.String)

}

I feel like getResponse should be in the Request trait, or something since it's generic enough to only need the overridden endpoint - but not sure.
Any general recommendations on structuring this sort of thing would be helpful.


texts:
This is a working stack implementation using a linked list.  I'm just curious to know if this is a good way of doing it.  Any suggestions are welcome. Can we keep track of the number of elements in the stack using a count variable as used in the code?

#include <cstdlib>
#include<iostream>
using namespace std;

class node
{
 public:
    int data;
    node* next;
};

class StackusingList
{
public:
StackusingList(int max)
{
    top = NULL;
    maxnum = max;
    count=0;
}

void push(int element)
{
    if(count == maxnum)
            cout<<"stack is full";
    else
    {
        node *newTop = new node;
        if(top == NULL)
        {
            newTop->data = element;
            newTop->next = NULL;
            top = newTop;
            count++;
        }
        else
        {
            newTop->data = element;
            newTop->next = top;
            top = newTop;
            count++;
        }
    }
}

void pop()
{
    if(top == NULL)
            cout<< "nothing to pop";
    else
    {
        node * old = top;
        top = top->next;
        count--;
        delete(old);
    }
}
void print()
{
    node *temp;
    temp = top;
    while(temp!=NULL)
    {
        cout<<temp->data<<",";
        temp=temp->next;
    }
}
private:
    node *top;
    int count; //head
    int maxnum;
    int stackData;
};

int main(int argc, char** argv) {
    StackusingList *sl = new StackusingList(5);
    sl->push(1);
    sl->push(2);
    sl->push(3);
    sl->push(4);
    sl->push(5);
    sl->push(6);

    sl->pop();
    cout<<"new stack\n";
    sl->print();

    return 0;
}


texts:
I've seen the pattern:

<?php
  if ($node = node_load(30) && $node->type == 'bogus') {
    print $node->title . 'is bogus';
  }

But when I tried to use it I got a warning: variable not defined... Has this pattern of declaring variables while you loop in an if been deprecated?


texts:
I am trying to write a function that will count the occurrences of a pattern in a string without overlap. This is what I have right now.

size_t count(char *string, char *pat) {
    size_t patternLength = strlen(pat);
    size_t stringLength = strlen(string);
    size_t count = 0;
    char *compareString = malloc(patternLength + 1);

    for (int i = 0; i < stringLength; i++) {
        if (i + patternLength > stringLength) return count;
        strcpy(compareString, &string[i], i+patternLength);
        if (strcmp(compareString, pat) == 0) {
            count++;
            i--;
            i+=patternLength; /* non overlapping find */
        }

    }
    free(compareString);
    return count;
}


texts: Elevation to power function using class templates

texts:
I attached below a small working example of a function that is able to perform x^y. As it is possible to see the base (x) takes double and the power takes an int. As last the main loop will also round up or down the result accordingly.

Not always I have these type of formats, and I could have base as int and power as double or base as long int and power as additional type. How can I improve this function to make it more general with different type format using template template <class identifier> or/and template <typename identifier>?

#include <cmath>

using namespace std;

class Power {
public:
    double raiseToPower(double x, int power)
    {
        double result;
        int i;
        result = 1.0;
        for(i = 1; i <=power; i++){
            result = result*x;
        }
        return result;
    }

    double floor0(double num)
      {
        if( (num + 0.5) >= (int(num) + 1) )
        return int(num)+1;
        else
        return int(num);
    }
};

int main()
{
    double x;
    int i;
    Power example;
    std::cout<<"please enter the number"<<std::endl;
    std::cin>>x;
    std::cout<<"please enter the integer power that you want this number raised to"<<std::endl;
    std::cin>>i;
    std::cout<<"rise to power "<<i<<" is equal to "<<example.raiseToPower(x,i)<<std::endl;
    std::cout<<"the result rounded is "<< example.floor0(example.raiseToPower(x,i))<<std::endl;
}

Thank for any insight and point to the right direction.


texts:
I've been having problems with a client where the server would move a file on the server, the client would then try and access that file but get a FileNotFoundException. We believe this is due to the client not synchronising to the server properly.

To get around this I wrote the following method to wait for the file to arrive before it touches it, including a timeout:

private static async Task<bool> WaitForFile(string path, int timeout)
{
    CancellationTokenSource cts = new CancellationTokenSource();
    Task waiterTask = Task.Run(async() =>
    {
        while (!File.Exists(path))
        {
            await Task.Delay(10);
        }
    }, cts.Token);

    bool completed = await TimeoutAfter(waiterTask, timeout);
    if (!completed)
    {
        cts.Cancel();
    }

    return completed;
}

private static async Task<bool> TimeoutAfter(Task task, int timeout)
{
    CancellationTokenSource cts = new CancellationTokenSource();

    Task completedTask = await Task.WhenAny(task, Task.Delay(timeout, cts.Token));
    if (completedTask == task)
    {
        cts.Cancel();

        return true;
    }

    return false;
}


texts: Filtering numeric vectors by proximity to any elements of another vector in R

texts:
I frequently want to filter and select elements from a long (10,000s to millions of elements) vector in R.  Often, this vector is a column in a data.frame.  I am usually interested in rows of the vector that "match" any one of a separate list of 10 to 100 query values.  However, since these are experimental data (mass spectrometry data for anyone interested), the target values and the query value(s) do not need to match exactly.  They only need to match within a tolerance.

In the field I work in (mass spectrometry), the values are mass-to-charge ratios, or m/z values.  There are two systems for specifying the tolerance or precision desired for comparing two numbers.  The first is the ppm or "parts per million" tolerance, i.e., a relative measure of precision.  The second is in absolute values, which invariably have units of atomic mass units or Daltons.  This explains the variable names I use below.

filter_by_mz <- function(query_mzs, target_mzs, ppm = 10, mz_tol = NULL){
    # ensure that users only supply one mass tolerance argument (either ppm or mz_tol)
    if(!missing(ppm) & !missing(mz_tol)){
        stop("Only a single mz tolerance parameter {mz_tol or ppm} can be supplied, not both.")
    }

    # find min and max mzs
    if(missing(mz_tol)){
        min_mzs <- target_mzs * (1 - ppm / 1e6)
        max_mzs <- target_mzs * (1 + ppm / 1e6)
    } else{
        min_mzs <- target_mzs - mz_tol
        max_mzs <- target_mzs + mz_tol
    }

    # allocate boolean matrix
    n_rows <- length(query_mzs)
    n_cols <- length(target_mzs)
    bool_mat <- matrix(FALSE, nrow = n_rows, ncol = n_cols)

    # loop over target mzs to create columns of bool_mat
    for(idx in seq_along(target_mzs)){
        min_mz <- min_mzs[idx]
        max_mz <- max_mzs[idx]
        bool_mat[, idx] <- query_mzs >= min_mz & query_mzs <= max_mz
    }

    # apply any() to rows of matrix
    return(apply(bool_mat, FUN = any, MARGIN = 1))
}

Now my questions:

How can I get rid of the for loop?  It seems like a smart way of using apply or a similar function would obviate this loop.
Is the argument handling OK?  I wanted users of the function to be able supply either ppm or mz_tol, but not both.  Am I using missing() correctly?
Is the design correct?  As I mentioned, I frequently will invoke this function on the columns of a data.frame.  For example, I'd frequently need to do my_filtered_df <- filter_by_mz(my_df$mz, target_mz, ...).  Would it be better to write the function to work on data.frames rather than just vectors?


texts:
Similar to my recently asked question: Style-changing handler for an HTML drop-down box How can I compress down JS and almost automate it?

I tried changing up the old questions answer a bit but never could get it working as i'm very new to JS I mainly do PHP.

So I just need the following JS compressed and automated as much as possible like last question:

function seasonChange() {

if(document.getElementById('selectseason').value == "1"){
    if(document.getElementById('selectseason1episode').value != "1 - Death Has A Shadow") {
        document.getElementById('season1episodes').style.display = 'block';
        document.getElementById('season2episodes').style.display = 'none';
        document.getElementById('season3episodes').style.display = 'none';
        document.getElementById('s1buttons').style.display = 'block';
        document.getElementById('s2buttons').style.display = 'none';
        document.getElementById('s3buttons').style.display = 'none';
    } else {
        document.getElementById('season1episode1').style.display = 'inline-block';
        document.getElementById('season1episodes').style.display = 'block';
        document.getElementById('season2episodes').style.display = 'none';
        document.getElementById('season3episodes').style.display = 'none';
        document.getElementById('s1buttons').style.display = 'block';
        document.getElementById('s2buttons').style.display = 'none';
        document.getElementById('s3buttons').style.display = 'none';
    }
}

if(document.getElementById('selectseason').value == "2"){
    if(document.getElementById('selectseason2episode').value != "1 - Peter, Peter, Caviar Eater") {
        document.getElementById('season1episodes').style.display = 'none';
        document.getElementById('season2episodes').style.display = 'block';
        document.getElementById('season3episodes').style.display = 'none';
        document.getElementById('s1buttons').style.display = 'none';
        document.getElementById('s2buttons').style.display = 'block';
        document.getElementById('s3buttons').style.display = 'none';
    } else {
        document.getElementById('season2episode1').style.display = 'inline-block';
        document.getElementById('season1episodes').style.display = 'none';
        document.getElementById('season2episodes').style.display = 'block';
        document.getElementById('season3episodes').style.display = 'none';
        document.getElementById('s1buttons').style.display = 'none';
        document.getElementById('s2buttons').style.display = 'block';
        document.getElementById('s3buttons').style.display = 'none';
    }
}

if(document.getElementById('selectseason').value == "3"){
    if(document.getElementById('selectseason3episode').value != "1 - The Thin White Line") {
        document.getElementById('season1episodes').style.display = 'none';
        document.getElementById('season2episodes').style.display = 'none';
        document.getElementById('season3episodes').style.display = 'block';
        document.getElementById('s1buttons').style.display = 'none';
        document.getElementById('s2buttons').style.display = 'none';
        document.getElementById('s3buttons').style.display = 'block';
    } else {
        document.getElementById('season3episode1').style.display = 'inline-block';
        document.getElementById('season1episodes').style.display = 'none';
        document.getElementById('season2episodes').style.display = 'none';
        document.getElementById('season3episodes').style.display = 'block';
        document.getElementById('s1buttons').style.display = 'none';
        document.getElementById('s2buttons').style.display = 'none';
        document.getElementById('s3buttons').style.display = 'block';
    }
}

}

Note: I cant reply to questions about the code but all I will say is the select season . value == 1 bit is season one e.g. I have shown 3 examples but there could be more then 3 seasons so maybe compress and automate using that $i++ variable.


texts:
I'm trying to replace the use of raw pointers with smart pointers in my C++ code. The following bit is from my first attempt at a self-balancing binary tree, though there is nothing self-balancing at the moment. I am worried about some fundamental problems regarding the use of unique pointers.

template <typename K, typename D>
class rbtree {
    struct rbnode;
    typedef std::unique_ptr<rbnode> node_ptr;
    node_ptr root_;

    struct rbnode {
        node_ptr left, right;
        rbnode *parent;
        enum { Red, Black } color;
        D data;
        K key;
        rbnode():
            left(nullptr), right(nullptr), parent(nullptr),
            color(Red), data(0), key(0) {}
        rbnode(K k, D d):
            left(nullptr), right(nullptr), parent(nullptr),
            color(Red), data(d), key(k) {}
        rbnode(K k, D d, rbnode *p):
            left(nullptr), right(nullptr), parent(p),
            color(Red), data(d), key(k) {}
    };

    node_ptr insert_(node_ptr& node, node_ptr& parent, K& key, D& data);
    public:

        bool insert(K& key, D& data);
        void dfs(std::function<void (K& key, D& data)> visitor);
};

template <typename K, typename D>
void rbtree<K, D>::dfs(std::function<void (K& key, D& data)> visitor) {
}

template <typename K, typename D>
typename rbtree<K, D>::node_ptr rbtree<K, D>::insert_(
        node_ptr& node, node_ptr& parent, K& key, D& data) {
    if (node == 0) { node = node_ptr(new rbnode(key, data, parent.get())); }
    if (key == node->key) { throw "Key exists!"; }
    if (key < node->key) {
        node->left = std::move(insert_(node->left, node, key, data));
    } else {
        node->right = std::move(insert_(node->right, node, key, data));
    }
    return std::move(node);
}

template <typename K, typename D>
bool rbtree<K, D>::insert(K& key, D& data) {
    root_ = std::move(insert_(root_, root_, key, data));
    root_->color = rbnode::Black;
    return true;
}


texts: Project Euler #85: Find the rectangular grid with closest to 2M rectangles

texts:
For one place that I interviewed at (for a Python developer position) I worked with one of the devs on two Project Euler problems, one being problem 85. We talked through different approaches and came up with solutions together, but we coded separately. He seemed impressed that we were able to get through two problems. After the interview, he asked me to clean up the code and submit it, which you can see below. He never got back to me after I sent him the code. I'd like to know what's wrong with my code and not make the same mistakes again.

Problem 85

  By counting carefully it can be seen that a rectangular grid measuring 3 by 2 contains eighteen rectangles:

  Although there exists no rectangular grid that contains exactly two million rectangles, find the area of the grid with the nearest solution.

# problem85.py
# Project Euler
# Nicolas Hahn

# int m, int n -> # of rectangles that can be made from m*n rectangle
def numRectangles(m,n):
    return (m*n*(m+1)*(n+1))//4

# int 'num' -> side length of first square that has >='num' rectangles
def getLargestSquareLength(num):
    rectNum = 0
    length = 0
    while rectNum < num:
        length += 1
        rectNum = numRectangles(length,length)
    return length

# int 'num' -> area of rectangle with closest to 'num' rectangles
def closestTo(num):
    rects = []
    # start from a square, work towards a 1*n rectangle
    length = getLargestSquareLength(num)
    for i in range(1,length+1):
        m = length-i
        n = m+1
        # find closest rectangle to 'num' with width m
        while numRectangles(m,n) < num and m > 0:
            n += 1
        # store both the >num rectangle and <num rectangle with width m
        rects.append((m,n,numRectangles(m,n)))
        rects.append((m,n-1,numRectangles(m,n-1)))
    # get closest number of rectangles, then compute area
    m,n,r = sorted(rects, key=lambda k: abs(k[2]-num))[0]
    return m*n

def main():
    # correct answer = 2772
    print(closestTo(2000000))

if __name__ == "__main__":
    main()


texts: Random password generator with choice of three strengths

texts:
My code works fine but I definitely have unecessary repeat code. I'd like to use functions so I don't have repeat code. I would appreciate any advise on how to make my password generator code more concise.

I've tried looking through other forums but I couldn't find the answer I'm looking for.

import string
import random
lowerCase = string.ascii_lowercase[:26]
upperCase = string.ascii_uppercase[:26]
numberList = ["1","2","3","4","5","6","7","8","9"]
specialCharacters = ["*","&","@","!"]
responseList = ["weak","medium","strong"]
randomCharacters =[ ]
i=0

while True:
  choice = input("Want to create a password? To make your choice for your password strength, please respond with one of the following: weak/medium/strong. ")

  if choice in responseList:
    if choice == "weak":
      while i<=5:
        randomLetterLower = random.choice(lowerCase)
        randomCharacters.append(randomLetterLower)
        i += 1

    elif choice == "medium":
      while i<=4:
        randomLetterLower = random.choice(lowerCase)
        randomCharacters.append(randomLetterLower)
        randomLetterUpper = random.choice(upperCase)
        randomCharacters.append(randomLetterUpper)
        i += 1

    elif choice == "strong":
      while i<=1:
        randomLetterLower = random.choice(lowerCase)
        randomCharacters.append(randomLetterLower)
        randomLetterUpper = random.choice(upperCase)
        randomCharacters.append(randomLetterUpper)
        randomNumber = random.choice(numberList)
        randomCharacters.append(randomNumber)
        randomSpecialCharacter = random.choice(specialCharacters)
        randomCharacters.append(randomSpecialCharacter)
        i += 1

    output = " ".join(randomCharacters)
    print(output)
    i = 0
    randomCharacters =[]

  else:
    break


texts:
I have not worked with jQuery for years so my knowledge of it is extremely limited. I wrote the following form and received a comment elsewhere saying:

  This is some of the worst JavaScript I've seen. Your selectors are
  terrible ($('div#foo') instead of $('#foo')), you copy-paste code all
  over the place, you return false instead of preventing the default
  action alone, you manually concatenate your data string instead of
  using the JSON library, you compare things with "==" instead of
  "===".... This is just awful style and being a novice.

Most of the notes included in that comment doesn't make much sense to me, I haven't had my mind inside the insanity of Javascript for years now.

My question is, how do I upgrade my code to actually use good practice and up-to-date technique?

HTML:

<form name="contact" action="">
  <fieldset>
    Name
    <input type="text" name="name" id="name" size="30" value="" class="text-input" />
    This field is required.

    Return Email
    <input type="text" name="email" id="email" size="30" value="" class="text-input" />
    This field is required.

    Return Phone
    <input type="text" name="phone" id="phone" size="30" value="" class="text-input" />
    This field is required.

    <input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
  </fieldset>
</form>

Form validation:

  $(function() {
    $('.error').hide();
    $(".button").click(function() {
      // validate and process form here

      $('.error').hide();
      var name = $("input#name").val();
        if (name == "") {
        $("label#name_error").show();
        $("input#name").focus();
        return false;
      }
        var email = $("input#email").val();
        if (email == "") {
        $("label#email_error").show();
        $("input#email").focus();
        return false;
      }
        var phone = $("input#phone").val();
        if (phone == "") {
        $("label#phone_error").show();
        $("input#phone").focus();
        return false;
      }

    });
  });

Process form:

  var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
  //alert (dataString);return false;
  $.ajax({
    type: "POST",
    url: "bin/process.php",
    data: dataString,
    success: function() {
      $('#contact_form').html("

");
      $('#message').html("
Contact Form Submitted!
")
      .append("
We will be in touch soon.
")
      .hide()
      .fadeIn(1500, function() {
        $('#message').append("");
      });
    }
  });
  return false;


texts:
It is the case where data contains some field indicating what type of strategy should be picked.

I mean, I often ignore solving the problem like shown below and duplicate the problems that strategy pattern is out to solve in the first place. Is there a pattern for it or is it not viable at all in this case?

Recent example on how I have solved it:

public class MapRentalCostStrategy : IMapper<EquipmentType, IRentalCostStrategy>
{
    private readonly Dictionary<EquipmentType, IRentalCostStrategy> _knownRentalCostStrategy;

    public MapRentalCostStrategy(IMutablePriceConfiguration mutablePriceConfiguration)
    {
        _knownRentalCostStrategy = new Dictionary<EquipmentType, IRentalCostStrategy>
        {
            { EquipmentType.Heavy, new HeavyRentalCostStrategy(mutablePriceConfiguration)},
            { EquipmentType.Specialized, new SpecializedRentalCostStrategy(mutablePriceConfiguration)},
            { EquipmentType.Regular, new RegularRentalCostStrategy(mutablePriceConfiguration)}
        };
    }

    public Func<EquipmentType, IRentalCostStrategy> Create => equipment =>
    {
        if (!_knownRentalCostStrategy.ContainsKey(equipment))
            throw new ArgumentException();

        return _knownRentalCostStrategy[equipment];
    };
}

where EquipmentType is an enum.

Maybe I should inject a service that returns this dictionary? In any case, it seems I am delegating the responsibility (in this case its "object creation", it should not be mappers responsibility to deal with the instantiation of the dictionary).

Maybe I am on the wrong track? Is there a better way?


texts:
I am making a quiz game and every time you complete a stage, the next stage will be unlocked.

The Problem:
When I am at Stage 3 and finish it, Stage 4 is unlocked. But when I feel like I want to play stage 1 again and finish it, the unlocked stage reverts to only Stage 2.

The Code:

protected void stageCompleted(){

        //If the stage is completed unlock the next stage
        if(10-correctAnswers<=mistakesAllowed){
            SharedPreferences sharedPref = mContext.getSharedPreferences("saves",Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putInt("completeStages", stageNumber+1);
            editor.commit();

        }

And here is my Stages List.java file:

public class StagesActivity extends AppCompatActivity {

    List<Stage> stageList=new ArrayList<Stage>();
    Button backBtn;
    SharedPreferences.OnSharedPreferenceChangeListener onPrefsChangeListener;

    private ListView stagesListView;
    SharedPreferences sharedPref ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_stages);

       sharedPref = StagesActivity.this.getSharedPreferences("saves",Context.MODE_PRIVATE);
        stagesListView=findViewById(R.id.stages_list_view);
        backBtn=findViewById(R.id.back_btn);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        initListView();

        onPrefsChangeListener=new SharedPreferences.OnSharedPreferenceChangeListener() {
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
                initListView();
            }
        };

        sharedPref.registerOnSharedPreferenceChangeListener(onPrefsChangeListener);

    }

    public void initListView(){
        JSONTools.readFileWithStages(StagesActivity.this,stageList);
        int completeStages=sharedPref.getInt("completeStages",0);
        Log.d("COMPLETED","COM:"+completeStages);
        for(int i=0;i<stageList.size();i++){
            if(completeStages>=i)
            stageList.get(i).setEnabled(true);
        }

        StagesListAdapter adapter = new StagesListAdapter(StagesActivity.this,stageList);

        stagesListView.setAdapter(adapter);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        sharedPref.unregisterOnSharedPreferenceChangeListener(onPrefsChangeListener);
    }
}

Stages List after Completing Stage 1 again:

Even if I completed Stage 3 and unlocked Stage 4:


texts:
I have a RequestsExtensions class with two functions for sending GET/POST requests.

using System;
using System.Net;
using System.Text;

    public static class RequestsExtensions
    {
        /// <summary>
        /// Sending POST request.
        /// </summary>
        /// <param name="Url">Request Url.</param>
        /// <param name="Data">Data for request.</param>
        /// <returns>Response body.</returns>
        public static string HTTP_POST(string Url, string Data)
        {
            string Out = String.Empty;
            System.Net.WebRequest req = System.Net.WebRequest.Create(Url);
            try
            {
                req.Method = "POST";
                req.Timeout = 100000;
                req.ContentType = "application/x-www-form-urlencoded";
                byte[] sentData = Encoding.UTF8.GetBytes(Data);
                req.ContentLength = sentData.Length;
                using (System.IO.Stream sendStream = req.GetRequestStream())
                {
                    sendStream.Write(sentData, 0, sentData.Length);
                    sendStream.Close();
                }
                System.Net.WebResponse res = req.GetResponse();
                System.IO.Stream ReceiveStream = res.GetResponseStream();
                using (System.IO.StreamReader sr = new System.IO.StreamReader(ReceiveStream, Encoding.UTF8))
                {
                    Char[] read = new Char[256];
                    int count = sr.Read(read, 0, 256);

                    while (count > 0)
                    {
                        String str = new String(read, 0, count);
                        Out += str;
                        count = sr.Read(read, 0, 256);
                    }
                }
            }
            catch (ArgumentException ex)
            {
                Out = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message);
            }
            catch (WebException ex)
            {
                Out = string.Format("HTTP_ERROR :: WebException raised! :: {0}", ex.Message);
            }
            catch (Exception ex)
            {
                Out = string.Format("HTTP_ERROR :: Exception raised! :: {0}", ex.Message);
            }

            return Out;
        }

        /// <summary>
        /// Sending GET request.
        /// </summary>
        /// <param name="Url">Request Url.</param>
        /// <param name="Data">Data for request.</param>
        /// <returns>Response body.</returns>
        public static string HTTP_GET(string Url, string Data)
        {
            string Out = String.Empty;
            System.Net.WebRequest req = System.Net.WebRequest.Create(Url + (string.IsNullOrEmpty(Data) ? "" : "?" + Data));
            try
            {
                System.Net.WebResponse resp = req.GetResponse();
                using (System.IO.Stream stream = resp.GetResponseStream())
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(stream))
                    {
                        Out = sr.ReadToEnd();
                        sr.Close();
                    }
                }
            }
            catch (ArgumentException ex)
            {
                Out = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message);
            }
            catch (WebException ex)
            {
                Out = string.Format("HTTP_ERROR :: WebException raised! :: {0}", ex.Message);
            }
            catch (Exception ex)
            {
                Out = string.Format("HTTP_ERROR :: Exception raised! :: {0}", ex.Message);
            }

            return Out;
        }
    }

Do you see any improvement / issue?


texts: Function that adds commas between groups of 3 digits in a string

texts:
My program contains some very large integers and uses the GMP library. The output contains integers (probably small enough to fit into int). I would like to make the output easy to read by adding commas between every three digits with any left overs on the left side.

Examples:

1234 => 1,234
12345 => 12,345
123456 => 123,456
123 => 123

The input of the function would be a string representing an integer, because the value of the mpz_class would be converted to a string. I know there's been a lot of discussion of adding commas to int but not string. The mpz_class can't be converted to an int because it may be too big.

Here is what I have and it isn't pretty.

using namespace std;

/*add commas between groups of 3 digits with remainder on left side*/
string addCommas(string in)
{
    const int length = in.length();
    if(length < 4)
    {
        return in;
    }
    int inserted = 0;
    int i = length % 3;
    if(i == 0)
    {
        i = 3;
    }
    for(; i < length + inserted; i = i + 4)
    {
        in.insert(i, ",");
        inserted++;
    }
    return in;
}

Given its use in the program, it is guaranteed the input will not be a negative number. Though I still wonder if it's good to include a check? The program focuses on quick results. How can this code be more readable?


texts: Scala function to parse json with time fields to appropriate case classes. How can I write this better?

texts:
I have the below function which populates different time-related case classes based on what is present in the JSON input.
def parseTime(timeJson: JsValue) = {
   val day = (timeJson \ "day").getOrElse(JsString("")).as[JsString].value.toInt
   val week = (timeJson \ "month").getOrElse(JsString("")).as[JsString].value.toInt
   val month = (timeJson \ "month").getOrElse(JsString("")).as[JsString].value.toInt
   val year = (timeJson \ "year").getOrElse(JsString("")).as[JsString].value.toInt
   if (day != "") {
     YearMonthDay(
       year = year,
       month = month,
       day = day)
   }
   else if (month != "") {
     YearMonth(
       year = year,
       month = month
     )
   }
   else if (week != "") {
     YearWeek(
       year = year,
       week = week
     )
   }
   else {
     Year(year)
   }
 }

Is there a cleaner way to check whether specific fields are present in my tuple of 4 values (day, week, month, year)


texts: Tornado API example with Momoko and RealDictCursor

texts:
I'm learning Tornado and Momoko for an upcoming project and I made a simple API with a GET user/{id} endpoint that queries a database in order to search a User from a database I created before for another project.

Here's the code:

import tornado.ioloop
import tornado.web
import tornado.gen as gen
import momoko
from psycopg2.extras import RealDictCursor
from json import dumps
from datetime import date, datetime

def json_serial(obj):
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, (datetime, date)):
        return obj.isoformat()
    raise TypeError ("Type %s not serializable" % type(obj))

class UserHandler(tornado.web.RequestHandler):
    @property
    def db(self):
        return self.application.db
    @gen.coroutine
    def get(self, user_id):
        cursor = yield self.db.execute("SELECT u.username as username, u.\"isActive\", u.created as created FROM \"User\" u WHERE id = %s LIMIT 1", (user_id,), cursor_factory=RealDictCursor)
        result = cursor.fetchone()
        self.set_header("Content-Type", "application/json")
        self.write(dumps(result, default=json_serial))
        self.finish()

def get_app():
    app = tornado.web.Application([
            (r'/user/([1-9][0-9]*)', UserHandler)
        ])
    app.db = momoko.Pool(
            dsn="dbname=test user=test password=test host=localhost port=5432"
            )
    app.db.connect()
    return app

if __name__ == "__main__":
    app = get_app()
    app.listen(3000)
    print("Starting loop")
    tornado.ioloop.IOLoop.current().start()

What do you think about it? Is there a better way to initialize a Pool object?

Thanks for any feedback


texts: Java TreeMap.floorKey() equivalent for std::map

texts:
I wanted something equivalent to this Java program:

TreeMap<Integer,Integer> map = new TreeMap<Integer,Integer>();
    map.put(10, 100);
    map.put(20, 200);
    map.put(30, 300);
    map.put(40, 400);
    map.put(50, 500);
    map.put(60, 600);
    map.put(70, 700);
    map.put(80, 800);

    System.out.println(map.floorKey(5));
    System.out.println(map.floorKey(9));
    System.out.println(map.floorKey(10));
    System.out.println(map.floorKey(11));
    System.out.println(map.floorKey(90));

output:

null null 10 10 80

As there is no direct API to achieve the same in C++, I wrote the following code to implement a similar floorKey() function:

template <typename key,typename value>
int floorKey(map<key, value> input, int key)
{
    auto begin = input.begin();
    if (begin->first > key)//if key is less than the first key. It must retrun -1;
        return -1;

    auto end = input.end();
    end--;
    if (end->first < key)//if key is greater than last key, it must return last key
        return end->first;

    //if key is equal to any existing key, it should return the key
    auto find = input.find(key);

    if (find != input.end())
        return key;

    //Return the floor key for the given key
    auto lower = input.lower_bound(key);

    lower--;
    return lower->first;
}

Here's the test program:

int main()
{
    map<int, int> map;
    map.insert({ 10, 100 });
    map.insert({ 20, 200 });
    map.insert({ 30, 300 });
    map.insert({ 40, 400 });
    map.insert({ 50, 500 });
    map.insert({ 60, 600 });
    map.insert({ 70, 700 });
    map.insert({ 80, 800 });

    cout << floorKey(map, 5) << endl;
    cout << floorKey(map, 9) << endl;
    cout << floorKey(map, 10) << endl;
    cout << floorKey(map, 11) << endl;
    cout << floorKey(map, 90) << endl;
    return 0;
}

output:

-1 -1 10 10 80

Is there any better way to get the same?  Anything else I can improve?


texts: Replacing a string until it matches a certain length

texts:
I'm trying to make an SMS Shortner for a kata at Codewars:

  Your task is to shorten the message to 160 characters, starting from end, by replacing spaces with camelCase, as much as necessary.

I've tried with a while loop and although the logic is correct, it's taking too long to process my tests. How can I optmize this and what parts are taking longer than it could?

const shortener = (message) => {
  let r = message.split('').reverse().join('');
  while (r.length > 160) {
    r = r.replace(/([^\s]\s)/, (m,s) => s.trim().toUpperCase());
  }
  return r.split('').reverse().join('');
}


texts:
I have a method that takes in a String parameter, and uses NLTK to break the String down to sentences, then into words. Afterwards, it converts each word into lowercase, and finally creates a dictionary of the frequency of each word.

import nltk
from collections import Counter

def freq(string):
    f = Counter()
    sentence_list = nltk.tokenize.sent_tokenize(string)
    for sentence in sentence_list:
        words = nltk.word_tokenize(sentence)
        words = [word.lower() for word in words]
        for word in words:
            f[word] += 1
    return f

I'm supposed to optimize the above code further to result in faster preprocessing time, and am unsure how to do so. The return value should obviously be exactly the same as the above, so I'm expected to use nltk though not explicitly required to do so. I also have access to scipy, numpy and pandas though I'm not sure how they would help in this case.

Is there any way to speed up the code? Or, if not, any way to make the code at least more elegant (i.e. pythonic)?


texts:
I made a function to censor a certain word from a piece of text. Is there anything I should fix or do more efficiently? What are some other approaches I could have taken to detecting words and censoring them?(This took me a lot of time to brainstorm)

Also, I would appreciate it if you told me how you brainstorm how to write a program.

def detect_word_start(text,word):
    count = 0
    text_count = 0
    for x in text:
        text_count+=1
        if x == word[count]:
            count+=1
            if count == len(word):
                return text_count - len(word) + 1
        else:
            count = 0

def censor(text,word):
    word_start = detect_word_start(text,word)
    censored_text = ''
    count = 0
    for x in text:
        count += 1
        if count >= word_start and count < word_start+len(word):
            censored_text += '*'
        else:
            censored_text += x
        print(censored_text)


texts: Generic merge sort in C++ using a user-defined comparison function or the < operator by default

texts:
I wanted to implement a generic merge sort algorithm using the same interface as std::sort(). The interface takes first and last iterators to a range of elements in any container. The user has the option to provide a custom function that compares two elements; if none is provided, the operator < is used by default.

I handled the default case by creating a wrapper function that calls the real function using a lambda expression, but I'm wondering if there's a way to get rid of this second wrapper function.

Feedback on any aspect of the code is welcome.

template <class RandomAccessIterator, class Compare>
void mergesort(RandomAccessIterator first, RandomAccessIterator last, Compare comp)
{
    size_t n = last - first;

    if (n <= 1)
        return;

    size_t m = n / 2;

    mergesort(first, first + m, comp);
    mergesort(first + m, last, comp);

    std::vector<RandomAccessIterator::value_type> v(last - first);
    RandomAccessIterator itResult = v.begin();

    RandomAccessIterator itLower = first;
    RandomAccessIterator itUpper = first + m;

    while (itLower != first + m && itUpper != last)
        *(itResult++) = comp(*itLower, *itUpper) ? *(itLower++) : *(itUpper++);

    if (itUpper == last)
        std::copy(itLower, first + m, itResult);
    else
        std::copy(itUpper, last, itResult);

    std::copy(v.begin(), v.end(), first);
}

template <class RandomAccessIterator>
void mergesort(RandomAccessIterator first, RandomAccessIterator last)
{
    mergesort(first, last, [](RandomAccessIterator::value_type a, RandomAccessIterator::value_type b) { return a < b; });
}


texts:
I got caught in the trap of implementing my own data structure. I've created a very general tree structure, where each node gets one parent, some children, and holds a value.

I'm mostly looking for advice on how to make this code more idiomatic, but also functionality that might be missing from this class, or that isn't necessary. I would also like thoughts on how idiomatic the traverse function is, and if there's a better way to implement it.

function Node(value = 0, children = []) {
    this.value = value;
    this.children = children;
    this.parent = undefined;
}

Node.from = function(node) {
    let that = Object.assign(new Node(), node);
    that.parent = undefined;
    that.children = node.children.map(n => (Node.from(n), n.parent = that));
    return that;
};

Node.prototype.add = function(...children) {
    for (child of children) {
        child.parent = this;
        this.children.push(child);
    }
};

Node.Traversal = {
    BreadthFirst: 1,
    DepthFirst: 2
};

Node.prototype.traverse = function(callback, mode = Node.Traversal.BreadthFirst) {
    if (mode == Node.Traversal.BreadthFirst) {
        let nodes = [this];
        while (nodes.length > 0) {
            const current = nodes.shift();
            callback(current);
            nodes = nodes.concat(current.children);
        }
    } else if (mode == Node.Traversal.DepthFirst) {
        callback(this);
        this.children.forEach(n => n.traverse(callback, false));
    }
    return this;
};

Node.prototype.reduce = function(callback, initial, mode) {
    let acc = initial;
    this.traverse(n => acc = callback(acc, n), mode);
    return acc;
};

Node.prototype.every = function(callback) {
    return this.reduce((a, n) => a && callback(n), true);
};

Node.prototype.some = function(callback) {
    return this.reduce((a, n) => a || callback(n), false);
};

Node.prototype.find = function(callback, mode) {
    return this.reduce((a, n) => a || (callback(n)? n: false), false, mode);
};

Node.prototype.includes = function(value) {
    return this.some(n => n.value === value);
};


texts: Most common letter in string, trying to use idiomatic Ruby

texts:
The task:

  Write a method that takes in a string. Your method should return the
  most common letter in the array, and a count of how many times it
  appears.

Model solution:

def most_common_letter(string)
  most_common_letter = nil
  most_common_letter_count = nil

  idx1 = 0
  while idx1 < string.length
    letter = string[idx1]
    count = 0

    idx2 = 0
    while idx2 < string.length
      if string[idx2] == letter
        count += 1
      end
      idx2 += 1
    end

    if (most_common_letter_count == nil) || (count > most_common_letter_count)

      most_common_letter = letter
      most_common_letter_count = count
    end

    idx1 += 1
  end

  return [most_common_letter, most_common_letter_count]
end

My solution:

def most_common_letter(string)

most_common_letter = nil
most_common_letter_count = 0

string.delete(" ").each_char do |letter|
  letter_count = 0
  string.each_char {|test| letter_count+=1 if test == letter }

  most_common_letter = letter and most_common_letter_count = letter_count if letter_count > most_common_letter_count
end

[most_common_letter, most_common_letter_count]

end

I tried using more idiomatic Ruby to solve this beginner problem we got in the beginning of the course. I'm wondering about a few things:

Is using "and" as I did in the if statement idiomatic? I tried a few guesses as to what might work (&&, &, some random characters), but I haven't seen this before.
I think the delete method alters the original string, and from the wonderful people on this site I've learned that altering the original data is unwise. How else could I ignore the spaces?
How can I tighten this up?


texts: Trabb Pardo – Knuth - Algorithm in streams

texts:
Trabb Pardo and Knuth devised this simple procedure as a way to explore the functionality of various languages. The wiki page describes it as:

  The Trabb Pardo–Knuth algorithm is a program introduced by Donald Knuth and Luis Trabb Pardo to illustrate the evolution of computer programming languages.

The algorithm is simple:

ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item in sequence S
    call a function to do an operation
    if result overflows
        alert user
    else
        print result

The standard 'function' is to calculate the following:

$$
    f(x) = \sqrt{|x|} + 5 \times x^3
$$

The limiting factor is traditionally the value 400.0.

Here's the Java 8 code to accomplish the traditional 11 input values:

import java.util.Arrays;
import java.util.Scanner;
import java.util.function.IntToDoubleFunction;
import java.util.stream.IntStream;

public class TPK {

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in);) {
            int[] values = IntStream.generate(scanner::nextInt).limit(11).toArray();
            int[] reversed = IntStream.range(0, values.length)
                    .map(index -> values[values.length - index - 1]).toArray();
            IntToDoubleFunction function =
                    val -> Math.sqrt(Math.abs(val)) + 5 * val * val * val;
            Arrays.stream(reversed)
                    .mapToDouble(function)
                    .forEach(val -> System.out.println(
                            val > 400.0 ? "TOO LARGE" : String.format("%.5f", val)));
        }
    }

}


texts: Is this the right way to do lambda method chaining in python?

texts:
I come from java background and I am trying to implement lambda chaining in Python. Below is my code
li = ["amol", "vikas", "rahul"]
li2 = list(filter(lambda n: (n == "Amol"), list(map(lambda name: (name.capitalize()), li))))
print(li2)

This Function will

Capitalize the names
Filter the names with "Amol"

Currently the code is running well but it seems to be cluttered and complicated when compared to java


texts: Putting in order my two packages and possibly merging them

texts:
I am making an application which fetches tweets for a specified amount of time, then inserts those tweets in a database and when the user presses another button the top n words and the hashtags will be shown.

This is my Twitter package:

[Package]Twitter
     >[Class]TwitterTools.java

This is my Analyzing package:

[Package]Analyzing
         >[Class]WordCounting.java

This is the TwitterTools class:

public class TwitterTools {

    public static List<Status> search(Query query) {
    }

    public static void filterTweetsBasedOnCity(List<Status> tweets, final String city) {
    }

    public static Query queryMaker(final String keywords, final Date since,
            final Date until, final int count) {
    }
}

search - returns a list of status based on a query
filterTweetsBasedOnCity - deletes status from a list if they were not made in a certain city
queryMaker - makes a query based on the parameters

This is the WordCounting class:

public class WordCounting {

    public static String getHtmlTable(final List<String[]> words, final List<String[]> hashtags) {
    }

    public static Stream<Map.Entry<String, Long>> getTopWords(final int topX, final Stream<String> words) {
    }

    public static String listToHtmlTable(List<Map.Entry<String, Long>> topEntries, final String title) {
    }
}

getHtmlTable - returns the html table of the top X words
getTopWords - returns a stream of the top words
listToHtmlTable - converts a list to an html table

My question is how should I arrange these two packages. Should I merge them since they have only one class each? Should I split them even more by having some of the functions in another class?


texts: Creating a new item or updating an existing item on page load

texts:
When the page loads, it checks to see if the user is trying to update an existing book or create a new book.

Something about my code just doesn't seem right.  It feels cumbersome and not very logical. Could someone put me out of my misery and let me know that I wrote this bit ok?

Public Property modID As Int32

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim bookID = Request.QueryString("bookID")

If Not String.IsNullOrWhiteSpace(bookID) Then
        newBook = False
    Else
        newBook = True
        Create()   'create a new book
        bookID = modID.ToString
    End If

    If Not newBook Then
        commitData()   'saves data on form
    End If

    If Not IsPostBack And Not newBook Then
        Page.DataBind()
        populateControls()    'populate my dropdown lists and radio/checkbox controls
        populateDatasets()    'load datasets to be used later
    End If

End Sub

Public Sub Create()
    'create a new book
    newBook = False
    Using dbcon As New SqlConnection(DBUtilities.ConnectionStringDefault)
        dbcon.Open()
        Dim cmd As New SqlCommand(CreateSQL, dbcon)
        cmd.Parameters.Add(New SqlParameter("@authorID", currentUser))
        modID = DirectCast(cmd.ExecuteScalar(), Int32)
    End Using
    navmod = NavbookFactory.Getbook(CInt(modID))
    populateNewBook()
End Sub


texts: Simple object oriented console calculator

texts:
I'd like to learn OOP. Could someone check my code and tell me how to improve it?

package com.company;

import java.util.InputMismatchException;
import java.util.Scanner;

public class CalculatorApp {
    private static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) {
        System.out.println("Write two numbers and +, -, * or / sign");
        char operator = 0;
        double firstNum = 0;
        double secondNum = 0;
        try {
            firstNum = scanner.nextDouble();
            secondNum = scanner.nextDouble();
            operator = scanner.next().charAt(0);
        } catch (InputMismatchException ime) {
            System.out.println("invalid input");
        } finally {
            if (operator != '+' & operator != '-' & operator != '*' & operator != '/') {
                throw new InputMismatchException();
            }
            Calculator calculator = new Calculator(firstNum, secondNum,    operator);
            System.out.println(calculator.makeCalculation());
        }
    }
}

Calculator class:

package com.company;

import java.util.HashMap;
import java.util.Map;

public class Calculator {
    private char operation;
    private double operand1;
    private double operand2;
    private Map<Character, Operation> operationMap = new HashMap<>();

    public Calculator(double operand1, double operand2, char operation) {
        this.operand1 = operand1;
        this.operand2 = operand2;
        this.operation = operation;

        operationMap.put('+', new Addition());
        operationMap.put('-', new Subtraction());
        operationMap.put('*', new Multiplication());
        operationMap.put('/', new Division());
    }

    public double makeCalculation() {
        Operation operationMapValue = null;
        if (operationMap.containsKey(operation)) {
            operationMapValue = operationMap.get(operation);
            System.out.println(operationMap.get(operation));
        } else {
            System.out.println("Invalid sign");
        }
        return operationMapValue.calculateResult(operand1, operand2);
    }
}

Operation interface:

package com.company;

public interface Operation {
    double calculateResult(double left, double right);
}

One of implementing classes:

package com.company;

public class Addition implements Operation {
    @Override
    public double calculateResult(double left, double right) {
        return left + right;
    }
}

And Tests:

package com.company;

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class CalculatorTest {
    Calculator calc = new Calculator(6.0, 2.0, '+');

    @Test
    void addsTwoNumbers() {
        assertEquals(8.0, calc.makeCalculation());
    }

    Calculator calc2 = new Calculator(6.0, 2.0, '-');
    @Test
    void subtractsTwoNumbers() {
        assertEquals(4.0, calc2.makeCalculation());
    }

    Calculator calc3 = new Calculator(6.0, 2.0, '*');
    @Test
    void multipliesTwoNumbers() {
        assertEquals(12.0, calc3.makeCalculation());
    }

    Calculator calc4 = new Calculator(6.0, 2.0, '/');
    @Test
    void dividesTwoNumbers() {
        assertEquals(3.0, calc4.makeCalculation());
    }
}


texts:
I'm trying to get all files paths and names to index them in my database for faster search in future. I have used multithreading and parallel classes, but I'm couldn't get the performance I expected. There is an app named "Search Everything," which indexes all my files in less than 2 minutes, but my code takes much longer. I checked Windows Task Manager and it was my hard drive limiting my code it was getting to 100% of usage. I know that's normal, but how did "Search Everything" do that? is there another way, maybe reading data from master file table or something?

void GetFiles(string dir)
        {
            Task.Factory.StartNew(() =>
            {
                try
                {
                    files.AddRange(Directory.EnumerateFiles(dir));
                    Task.Factory.StartNew(() => {
                        Parallel.ForEach(Directory.EnumerateDirectories(dir), single => {
                            GetFiles(single);
                        });
                    });
                }
                catch { }
            });
        }


texts:
I decided to step out of my comfort zone (Java) and try out Python. I wrote a very simple reverser.py and want it to be reviewed.

"""
This python script basically takes a string and reverses it.

This python script can be used as a command line script as well as a separate
module.
"""
import sys

def reverse(message):
    """
    This function takes a string and reverses it, so as to somewhat obfuscate
     it.

    :param message: The unencrypted text message to be reversed.
    """
    text = ''
    for character in message:
        text = character + text
    return text

if __name__ == '__main__':
    numberOfArgs = len(sys.argv)

    message = ''
    if numberOfArgs == 1:  # i.e. the program name only
        message = input('Please enter the text to be encrypted : ')
    elif numberOfArgs == 2:
        message = sys.argv[1]
    else:
        print('Incorrect number of arguments : %d\n' % numberOfArgs)
        print('Usage: python3 reverseCipher [unencrypted string]')
        exit(2)  # '2' stands for command-line syntax errors in unix

    print(reverse(message))

Examples in the terminal:

$ python3 reverser.py

Please enter the text to be encrypted : I understand that text manipulation in python is quite easy.
.ysae etiuq si nohtyp ni noitalupinam txet taht dnatsrednu I

$ python3 reverser.py "I am just starting out with python"

nohtyp htiw tuo gnitrats tsuj ma I

It would be great if I would be advised about:

Code style and idioms
The required mindset (for I have one for Java)
Anything that can help me learn the language


texts: What is the most memory efficient way to load big arrays into PHP script?

texts:
I have a few big arrays stored in separate files that are included into PHP as and when they are required:

Array File:

<?php
 $cty_arr["af"] = "Afghanistan";
 $cty_arr["ax"] = "Åland Islands";
 $cty_arr["al"] = "Albania";
 $cty_arr["dz"] = "Algeria";
 $cty_arr["as"] = "American Samoa";
...
?>

Main Script:

<?php
 require("/var/www/include/array_file.php");
...
?>

I am not very sure how PHP utilizes memory, but I have this thought that some RAM is allocated to store the big array for each instance that the script is run. Since these arrays are static, could there be a better way of loading such arrays to achieve some memory savings?


texts:
I am curious to know if there is a faster, better, and more efficient way to accomplish this program that acquires employee information:

    <?php
session_start();
//require 'functions.php';
//require 'DB.php';
$employeeID = $_SESSION['employeeID'];
$clockIn = $_GET['clockIn'];
$clockOut = $_GET['clockOut'];
$timeToday = date("g:i a");
$dateToday = date("m/d/y");
$jobDescription = $_GET['jobDesc'];
$equipType = $_GET['equipTypeRan'];
$unitNumber = $_GET['unitNumber'];
$unitHours = $_GET['unitHours'];
if (isset($clockIn)) {

    echo "You clocked in at: " . $timeToday . " on " . $dateToday;

    try {
    $conn = new PDO('mysql:host=localhost;dbname=timecard', 'username', 'password');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare('INSERT INTO timeRecords (employeeID, date, timeIn) VALUES (:employeeID, :dateToday, :timeIn)');

    $stmt->execute(array(':employeeID' => $_SESSION['employeeID'], ':dateToday' => $dateToday, ':timeIn' => $timeToday));

    } catch(PDOException $e){
        echo'ERROR: ' . $e->getMessage();
    }
    $conn = null;

} else if (isset($clockOut)) {

        try {
    $conn = new PDO('mysql:host=localhost;dbname=timecard', 'username', 'password');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare('UPDATE `timeRecords` SET `timeOut`= :timeOut WHERE `date`= :dateToday AND `employeeID`= :employeeID');

    $stmt->execute(array(':employeeID' => $_SESSION['employeeID'],':dateToday' => $dateToday, ':timeOut' => $timeToday));

    $stmt = $conn->prepare('SELECT `timeIn` FROM `timeRecords` WHERE `date`= :dateToday AND `employeeID` = :employeeID');
    $stmt->execute(array(':employeeID' => $_SESSION['employeeID'], ':dateToday' => $dateToday));
    $stmt->setFetchMode(PDO::FETCH_BOTH);
    $results = $stmt->fetch();
    $timeInDB = $results[0];

    } catch(PDOException $e){
        echo'ERROR: ' . $e->getMessage();
    }

    $time_one = new DateTime($timeInDB);
    $time_two = new DateTime($timeToday);
    $difference = $time_one->diff($time_two);

    echo "You clocked in at: " . $timeInDB . "
";
    echo "You clocked out at: " . $timeToday . "
";

    echo $difference->format('Total working time %h hours %i minutes');

}else {

try{
    $conn = new PDO('mysql:host=localhost;dbname=timecard', 'username', 'password');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT COUNT(*) FROM timeRecords WHERE `timeOut` IS NULL AND `employeeID`= :employeeID AND `date`= :dateToday");

    $stmt->execute(array(':employeeID' => $employeeID, ':dateToday' => $dateToday));
    } catch(PDOException $e){
        echo'ERROR: ' . $e->getMessage();
    }

if($stmt->fetchColumn() > 0){

    try{
    $conn = new PDO('mysql:host=localhost;dbname=timecard', 'username', 'password');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare('UPDATE `timeRecords` SET `jobDescription`= :jobDescription, `equipType`= :equipType, `unitNumber`= :unitNumber, `unitHours`= :unitHours,
                            `timeOut`= :timeOut WHERE `employeeID`= :employeeID AND `date`= :dateToday AND `timeOut` IS NULL');

    $stmt->execute(array(':employeeID' => $employeeID, ':timeOut' => $timeToday, ':dateToday' => $dateToday, ':jobDescription' => $jobDescription,
                         ':equipType' => $equipType, ':unitNumber' => $unitNumber, ':unitHours' => $unitHours));

    $stmt = $conn->prepare('INSERT INTO timeRecords (employeeID, date, timeIn) VALUES (:employeeID, :dateToday, :timeIn)');
    $stmt ->execute(array(':employeeID' => $employeeID, ':dateToday'=> $dateToday, ':timeIn' => $timeToday));
    } catch(PDOException $e){
        echo'ERROR: ' . $e->getMessage();
    }

    echo "There was an update";
} else {
    echo "There was no Match";
}

    require 'summary.php';

}

?>