texts: Show and Hide group of classes based on data attributes

texts:
Somebody please verify this code. Is this efficient? please tell me modular way to accomplish this task.

  Updated

  I want to add show class to data-targetand remove
  show class from data-group Just like happening in an accordion. I wanted to know that this code is perfect for that scenario. I'm new here please let know if did not provide enough information.

$(function () {
  $(document).on("click", ".showHide", function() {
    var hideClasses = $(this).data("group").split(" ");
    var showClasses = $(this).data("target").split(" ");

    $.each(hideClasses, function(k, v) {
      $("."+v).removeClass("show");
    });
    $.each(showClasses, function(k, v) {
      $("."+v).addClass("show");
    });
  });
});

HTML tag

Remeber Password?

  More Info

  Please find the pen I have the working link. Try clicking on login, sign up, forgot password password and the stay relaxed.

CodePen Link


texts:
I am constructing a selector on every radio button click. Since I am using the table repeatedly on every radio click, I cached it like:

var $t1 = $("#tableone");

but inside the radio check event, I need to retrieve the selector to construct a string.

Approach 1:

$radio.click(function () {
        var temp = $t1.selector + " ." + $(this).attr("mobnum");

Note: If I do not $t1.selector, it comes as [object][Object] which I do not want, so I have to use $t1.selector.

Since I am using $t1.selector to construct temp every time radio is clicked, is there still a benefit caching the table at the beginning?

Approach 2:

$radio.click(function () {
var temp = $("#tableone") + " ." + $(this).attr("mobnum");

Which one's better?


texts: Print a square graph and dot based on co-ordinates

texts:
I've written a simple script, that takes a 0, 0 style co-ordinate input, following the pattern of:
$$0 \le n \le 9$$
Tacked onto the end of the output program, is a simple script that runs through all iterations of 0,0 - 9, 9.
Below is a gif of that.

Note: This code DOES not map multiple, I am not asking how you can map multiple, I am asking for suggestions on my working code.

import os
import time

def plot_point(x, y):
    os.system('cls') if os.name == 'nt' else os.system('clear')
    print 'Printing', x, y # Turned on for single use, off for mass use
    row_with_entry = ''
    rows = []
    for i in range(x):
        rows.append([i, '|_' * 10 + '|'])

    for i in range(y):
        row_with_entry += '|_'

    row_with_entry += '|*|'

    for i in range(y, 9):
        row_with_entry += '_|'

    rows.append([x, row_with_entry])

    for i in range(int(x), 9):
        rows.append([i, '|_' * 10 + '|'])

    for i in rows:
        print i[1]

    time.sleep(.05) # Just for purpose of demonstration

for i in range(9, 0, -1):
    for k in range(9, 0, -1):
        if i == 1:
            if k == 1:
                plot_point(i, k)
                plot_point(i, k - 1)
                for n in range(9, 0, -1):
                    plot_point(0, n - 1)
                plot_point(0, 0)
            else:
                plot_point(i, k)
        else:
            plot_point(i, k)
            plot_point(i, k - 1)


texts:
Previous question:

Java application for finding permutations efficiently>

I have changed quite a bit of code, and need some more reviews.

class Permutations {

    static long factorial(int num){
        long factorial = num;
        for (int forBlockvar = num; forBlockvar > 1; forBlockvar--) {
            factorial = factorial * forBlockvar;
        }
        return factorial / num;
    }

    public static void main(String[] args){
        long FactNmR;
        int n = 8;
        int num = n;
        int r = 6;
        int nMr = n - r;

        long FactN = factorial(num);

        if (nMr == 2) {
            FactNmR = 2;
        }
        else if (nMr <= 1){
            FactNmR = 1;
        }
        else if (nMr >= 2) {
            num = nMr;
            FactNmR = factorial(num);
        }

        long permutations = FactN;

        permutations = permutations / FactNmR;

        System.out.println(permutations);
    }
}


texts: Multithreaded number printer in ordered manner

texts:
On recent interview I was asked to write program that print "Zero" and "One" to stdout from different threads, but in ordered manner:
zero
one
zero
one
zero
one
...

Now I decided to write more generalized solution and this is my first attempt:
#include <string>
#include <vector>
#include <mutex>
#include <initializer_list>
#include <condition_variable>
#include <thread>
#include <iostream>

struct OrderNumberPrinter
{
    OrderNumberPrinter(const std::initializer_list<std::string>& list)
        : m_len(list.size())
        , m_cv(list.size())
    {
        size_t num = 0;
        for(auto it = list.begin(); it != list.end(); ++it, ++num)
        {
            m_workers.emplace_back([this, num, message = *it](){
                while(true)
                {
                    std::unique_lock<std::mutex> lock(m_printLock);
                    m_cv[num].wait(lock, [this, num](){ return m_current == num; });
                    std::cout << message << "\n";
                    std::this_thread::sleep_for(std::chrono::seconds(1));
                    ++m_current;
                    if (m_current == m_len)
                    {
                        m_current = 0;
                    }
                    m_cv[m_current].notify_one();
                }
            });
        }
    }

    ~OrderNumberPrinter()
    {
        for(auto& w: m_workers)
        {
            if (w.joinable())
            {
                w.join();
            }
        }
    }
private:
    int m_len = 0;
    int m_current = 0;
    std::vector<std::condition_variable> m_cv;
    std::mutex m_printLock;
    std::vector<std::thread> m_workers;
};

int main(int argc, char* argv[])
{
    OrderNumberPrinter printer = {"zero", "one", "two", "three"};
    return 0;
}


texts: Increase the speed of this python code for text processing

texts:
I need to iterate through a file of words and perform tests on them.

import multiprocessing
import datetime

class line_Worker(object):
    def worker(self, chunks):
        for l in chunks:
            num = 0
            for num in range(100):
                print l, num
        return

if __name__ == '__main__':
    lines = [line.rstrip('\n') for line in open('words.txt')] #opens file and saves to list
    chunkNum = len(lines) / 26
    wordLists = [lines[x:x + chunkNum] for x in range(0, len(lines), chunkNum)]#divides list by 4 and saves to list of lists
    jobs = []
    timeStart = str(datetime.datetime.now())

    for i in range(27):
        p = multiprocessing.Process(target=line_Worker().worker, args=(wordLists[i],))
        jobs.append(p)
        p.start()
    for p in jobs:
        p.join()  # wait for the process to finish

    timeStop = str(datetime.datetime.now())

    print timeStart
    print timeStop

I have a problem set of 35,498,500 individual lines, and I need to try to get it to run in roughly 3 minutes. The current run times are 16 minutes.

Is there any way to speed this up? Thanks all!


texts: Minimum number of swaps for two 2D arrays to make the first one identical to other

texts:
Bit Swapping

You’re given two binary matrices, m rows and n columns. Both matrices have the same size i.e. same number of rows and same number of columns. Each cell is a bit either 0 or 1. You need to find the minimum number of swaps are required in the first matrix in order for it’s arrangement to match that of the second. If the matched arrangement can never be achieved output -1.

Input Format

The first line contains a single integer t, denoting the number of test cases.
The first line of each test case contains two space separated integers m and n denoting the number of rows and number of columns. Next m lines each contains n elements of the first matrix. Next m lines each contains n elements of the second matrix.

Output Format

For each test case print the minimum swaps.

Constraints

1 <= t <= 1000

1 <= m <= 100

1 <= n <= 100

Sample Input

6
2 2
00
11
01
10
2 2
00
11
00
11
2 2
00
11
01
00
1 7
0011011
0101101
1 1
0
1
1 1
0
0

Output:

1
0
-1
2
-1
0

Code:

for each in range(int(input())): #t test cases
    m = int(input().split(' ')[0]) # m and n dimensions out of which im using m only
    a1 = []
    a2 = []
    for i in range(m): # first matrix input
        a1 += [int(k) for j in input() for k in j]
    for i in range(m): # second matrix input
        a2 += [int(k) for j in input() for k in j]
    if a1.count(1) != a2.count(1): # counting if count of 1 and 0 are same in both matrix
        print(-1) # if not then print -1
    else:
        c = 0
        for j in range(len(a1)):
            if a1[j] != a2[j]:
                c += 1
        print(c//2) # if yes then print minimum number of swaps

This is a Code Golf contest where shorter source awards higher score. Score is calculated by the following formula

(1 - s/10000)*100

where s is the number of characters in your source.

For example, if a correct source uses 1000 characters, a score of (1 - 1000/10000)*100 i.e. 90 will be awarded. The source limit is 10000 characters.


texts: Beginner solution to basic quiz exercise, a la Gophercises

texts:
I just started golang development about two weeks ago and recently finished the recommended introduction book.

I'm now working my way through Gophercises - a sort of collection of exercises to improve beginner's understanding of Golang through small projects.

This is my solution to the first project: writing a quiz (cli-)application.

The requirements are simple:

Read a csv file, each line consisting of a question and an answer:

5+5,10
1+1,2
8+3,11
1+2,3
8+6,14
3+1,4
1+4,5
5+1,6
2+3,5
3+3,6
2+4,6
5+2,7

Print the question to the user
Validate if the supplied answer is correct.
Print the correct answers.

Here is my solution to the problem:

package main

import (
    "bufio"
    "encoding/csv"
    "flag"
    "fmt"
    "io"
    "log"
    "os"
)

type q struct {
    question, answer string
}

func (q q) ask() bool {
    fmt.Println(q.question, " equals: ")
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan()
    if scanner.Err() != nil {
        log.Fatal(scanner.Err())
    }
    if scanner.Text() == q.answer {
        return true
    }
    return false
}

func quizLoop(path string, verbose bool) {
    // Loop should:
    // 1. Read records line by line
    // 2. Ask the question (i/o)
    // 3. Keep score.
    file, err := os.Open(path)
    correct, lines := 0, 0

    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    reader := csv.NewReader(file)
    for {
        record, err := reader.Read()
        if err != nil {
            if err == io.EOF {
                break
            }
            log.Fatal(err)
        }
        q := q{question: record[0], answer: record[1]}
        if q.ask() {
            if verbose {
                fmt.Println("Correct")
            }
            correct++
        } else if verbose {
            fmt.Println("Incorrect")
        }
        lines++
    }
    fmt.Printf("You had %d/%d correct answers!\n", correct, lines)
}

func main() {
    // Setup flags.
    p := flag.String("path", "problems.csv", "Specify the path to the quiz questions.")
    v := flag.Bool("verbose", false, "A boolean value to check if you want the program to be verbose or not.")
    flag.Parse()

    // Invoke loop.
    quizLoop(*p, *v)
}

As mentioned in my introduction I am rather new to the language, and couldn't see any caveats where it could have been beneficial to use things like interfaces or go routines in this particular project.

These are the things I'm the most interested in having reviewed:

Best Practices
Refactoring
How to use more advanced functionality to solve it (ie. go routines or interfaces)
Adding unit tests to it. What can be tested?
Overall design


texts:
My script looks for handshake files in an input folder to determine whether certain processes have completed.  If it finds them, it will update the database with the current time stamp.

Things I am wondering:

My update_db function takes 5 parameters.  I have heard that in that case there is probably a better way to do it.  Would this be a good candidate for creating a class and using an OO approach?
I am eventually going to be using a datetime to compare against the handshake timestamps, would it be difficult to somehow pull the file dates off our Linux server instead of creating them in the script?
Finally, any inconsistencies, ways I can simplify/improve my code.  I am a new programmer of only 6 months, and love to learn:)

Here's the code:

def main():

    # Get current time stamp
    now = datetime.now()
    formatted_dt = '{0}/{1}/{2}-{3}:{4}:{5}'.format(now.month,
                                                    now.day,
                                                    now.year,
                                                    now.hour,
                                                    now.minute,
                                                    now.second)
    # Connect to db
    sqlite_file = '/bcs/lgnt/clientapp/csvbill/database/csv.db'
    csv_connection = sqlite3.connect(sqlite_file)
    c = csv_connection.cursor()

    file_type = ['auditv2', 'handshake']

    # Check for files that don't have first hshake
    c.execute('SELECT pivot_id FROM aud_qty WHERE hshake1 is NULL')
    piv_id_list = [str(x[0]) for x in c.fetchall()]
    missing_list = update_db('CSV1000', file_type[0], piv_id_list, c, formatted_dt)
    # hshake1_miss = check_hshake('CSV1000', file_type[0], piv_id_list)
    # print(hshake1_miss)
    csv_connection.commit()
    csv_connection.close()

def update_db(proj_id, audit_type, piv_id_list, db_cursor, time_stamp):

    # chdir('/prod/bcs/lgnp/input')
    # prod_list = listdir('/prod/bcs/lgnp/input/')
    # for testing
    chdir('/bcs/lgnt/input')
    prod_list = listdir('/bcs/lgnt/input/')
    hshake_list = []

    for i, e in enumerate(prod_list):
        prod_list[i] = prod_list[i].split('_') # Field 6 is auditv2, Field 7 is the Pivot ID
    # Get only the Pivot ID
    for i, e in enumerate(prod_list):
        try:
            if prod_list[i][0] == proj_id and prod_list[i][6] == audit_type:
                hshake_list.append(prod_list[i][7])
        except IndexError:
                pass
    # pdb.set_trace()
    for i, e in enumerate(hshake_list):
        if hshake_list[i] in piv_id_list:
            print(hshake_list[i])
            # pdb.set_trace()
            db_cursor.execute('UPDATE aud_qty SET hshake1 = ? WHERE pivot_id = ?',
                             (time_stamp, hshake_list[i]))
            piv_id_list.remove(hshake_list[i])
    print(piv_id_list)
    return piv_id_list


texts:
I have this method which reverses a list of numbers. For example, if the given input is { 1232, 3455, 6071 }, it will return {2321, 5543, 1706}

public static List<int> ReverseIntegerList_Array(List<int> intList)
    {
        var newIntList = new List<int>();

        foreach (var numbers in intList)
        {
            var charNums = numbers.ToString();
            char[] arrNums = new char[charNums.Length];
            for (int x = 0; x < charNums.Length;x++)
            {
                arrNums[x] = charNums[charNums.Length-1-x];
            }
            newIntList.Add(Convert.ToInt32(string.Join("",arrNums)));

        }
        return newIntList;
    }

Can I reduce the space complexity further by not using an extra list object to store the result and return the result by overwriting the existing list object (defined in the method parameter)?

Found the way already.

 public static List<int> ReverseIntegerList_Array3(List<int> intList)
    {
        // var newIntList = new List<int>();
        for (int i = 0; i < intList.Count; i++)
        {

            var charNums = intList[i].ToString();
            intList[i] = 0; // Clear it.
            char[] arrNums = new char[charNums.Length];
            for (int x = 0; x < charNums.Length; x++)
            {
                arrNums[x] = charNums[charNums.Length - 1 - x];
            }
            intList[i] = Convert.ToInt32(string.Join("", arrNums));
        }

        return intList;
    }

Is this solution okay in regards to space complexity?


texts:
I am beginner a 1st year cs student. I am taking CS50 and I completed the first week problem of implementing  Luhn Check algorithm. Though my solution  works I feel it's very sloppy and not efficient. Can someone please suggest how can I improve my solution? (It's a first-week problem so you are not intended to use array or functions.)

Here is the code:

#include<stdlib.h>
#include<cs50.h>
int main()
{
    long long x,j=0;
    int len,i,len_flag,flag=0,flag_val=0,sp_len=0,check_flag=0; //basic integers related  to loop etc
    int res,sum,fin_sum=0,h=0,d2_sum=0,d1_sum=0,ff_num=0; // variables  related to extracting numbers
    int sum_len=0,in_sum=0,in_fsum=0,len_sum=0,m=0; // extraing numbers from more than single  sum result
    int sum_f=0,sum_final=0;

    do{
        x = get_long("enter a valid card number \n");
        j=x;
        len_flag = 0;
        len = 0;
        while(len_flag!=1)
        {
          x = x / 10;
          if(x==0)
          {
            len_flag = 1;   //finding the lenght of the number
          }
          len++;
        }
        if(len==15||len==16||len==13)
        {
          flag = 1;
          sp_len =1;
        }
        else
        {
            flag=1;
        }

    }while(flag!=1);

    for(i=0;i<len;i++)
    {
       res = j % 10;
       j = j / 10;
       if(i%2!=0)
       {

        sum = res * 2;
        //printf("multi_res : %d \n",sum);
        len_flag = 0;
        sum_len = 0;
        len_sum = sum;
        while(len_flag!=1)
        {
            len_sum = len_sum / 10;
            if(len_sum==0)
            {
               len_flag=1;       // checking if the sum is more than single  digit
            }
            sum_len++;
            //printf("trig\n");
        }
        if(sum_len>1)
        {   x=0;
            while(x<sum_len)
            {
             in_sum = sum % 10;
             sum = sum/10;
             in_fsum = in_fsum + in_sum;
             //printf("double sum : %d \n",in_fsum);
             x++;

            }
        }

        fin_sum = fin_sum + sum;

       }
       if(i==len-1)
       {

         for(h=0;h < 1;h++)
         {
            fin_sum = fin_sum + in_fsum;
         }

         d1_sum = res;
       }

       else if(i%2==0)
       {
        sum_f = sum_f + res; // adding up the number that where not  x2
       }

       if(i==len-2)
       {
         d2_sum = res;     //5555555555554444
       }

    }

    sum_final = sum_f + fin_sum;

    //printf("sum_final : %d\n",sum_final);
    //printf("sum_f_final : %d\n",sum_f);
    //printf("sum_in_final : %d\n",fin_sum);

    if(sum_final%10==0)
    {
        flag_val=1; // checking if the number is valid
    }
    if(ff_num == 0)
    {
        ff_num = (d1_sum*10) + d2_sum;     //flip
    }

    do
    {
       if(sp_len==0)
       {
        printf("INVALID\n");
        check_flag=1;
        break;
       }
       if((flag==1&&flag_val==1&&ff_num==34)||ff_num==37)
       {
        printf("AMEX\n");
        check_flag=1;
        break;
       }
       else if(flag==1&&flag_val==1&&ff_num>50&&ff_num<56)
       {
        printf("MASTERCARD\n");
        check_flag=1;
        break;
       }
       else if(flag==1&&flag_val==1&&d1_sum==4)
       {
        printf("VISA\n");
        check_flag=1;
        break;
       }
       else
       {
        printf("INVALID\n");
        check_flag=1;
        break;
       }
    }while(check_flag!=1);

    return 0;

}

I felt like I was fixing a leak while writing the code. I would try to correct one thing and another thing would go wrong and this is the final result.

Thank you for your help. If the question was not asked properly please forgive me; it's my first time here.


texts: First Occurrence of Number in Binary Search?

texts:
I am trying to write a function, where given a sorted array, and a number, it returns the FIRST index of that number.

Is this correct? Code is in Ruby, but even if you don't know Ruby, you can pretty much understand the syntax.

def first(array, n)
        if(array.size == 0)
           return -1
        end

        l = 0
        u = array.size - 1

        #LOOP INVARIANT:
        # l <= startIndex <= u

        while( l != u)
         #LOOP TERMINATES when l = u.
         #this occurs if we reach the far right or far left without finding the #
         #or if we found the start index of the number

            m = (l+u)/2
            if(array[m] > n)
                u = m -1    # l <= startIndex <= u

            elsif(array[m] < n)
                l = m + 1   # l <= startIndex <= u

            elsif(array[m] == n)
                u = m       # l <= startIndex <= u

            end

            #LOOP always terminates because we're narrowing the range by changing l or u.
            #if there's 1 element, finding the midpoint won't narrow the range,
            #but the while condition ends the loop anyway.
        end

        if(array[u] == n)
           return u
        else
           return -1
        end

    end


texts: Making loop in CSS Stylus more efficient

texts:
I'm not sure if this could be more efficient because I don't think I should need 2 keyframe loops in addition to the for loop?

for i in (1..19)
.l:nth-child({i})
n = (20 - i)
height 0
if i >= 10
  margin-left ((n * n) * (1.25/n)) + 17 px
  box-shadow 0px 0px (n+4)px 0 rgba(40,70,200, 0.5),0px 0px (i+8)px 0 rgba(80,100,235, 0.45),0px 0px 14px 0 rgba(115,215,235, 0.35),0px 0px 23px 0 rgba(110,130,215, 0.5)
  width (n * 1.05) + 0px
  animation (heights- + i) 0.75s (n/80)s linear forwards
else
  margin-left ((i * i) * (1.25/i)) + 17 px
  box-shadow 0px 0px (i+4)px 0 rgba(40,70,200, 0.5),0px 0px (i+8)px 0 rgba(80,100,235, 0.45),0px 0px 14px 0 rgba(115,215,235, 0.35),0px 0px 23px 0 rgba(110,130,215, 0.5)
  width (i * 1.05) + 0px
  animation (heightsx- + i) 0.75s (i/80)s linear forwards

for i in (10..19)
n = (20 - i)
$keyframe-name = (heights- + i)
@keyframes {$keyframe-name}
  0%
    height 0
  91%
    height ((n + 4) * 1.4) px
  98%
    height ((i + 38) * 5.4) px
  100%
    height ((n + 38) * 4.4) px
    opacity (n/6)
    if i == 10
    height ((i + 43) * 4.4) px
    opacity (i/6)

for i in (1..9)
$keyframe-namex = (heightsx- + i)
@keyframes {$keyframe-namex}
  0%
    height 0
  91%
    height ((i + 4) * 1.4) px
  98%
    height ((i + 38) * 5.4) px
  100%
    height ((i + 38) * 4.4) px
    opacity (i/16)


texts:
I have written the following class which is supposed to act as a consumer of messages that are passed in from producers and forward them onto amazon SQS, I have made a compromise by starting the operation at the constructor and waiting and completing on it in the dispose method, I made this compromise to make the clients job of using this class easier and because I thought since the processorTask and the SQS client have to be disposed anyway then it should be fine to use the dispose method to make sure they are finished with their duties.

I would like it to be reviewed for any sort of improvement.

public class BatchMessagePublisher : IMessagePublisher
{
    private const int PublishBatchSize = 10;

    private readonly IAmazonSQS _sqsClient;
    private readonly ILogger<BatchMessagePublisher> _logger;
    private readonly string _queueUrl;
    private readonly bool _isFifo;
    private readonly BatchBlock<Message> _messageBatcher;
    private readonly Task _processorTask;

    public BatchMessagePublisher(IAmazonSQS sqsClient, ILogger<BatchMessagePublisher> logger, string queueUrl, bool isFifo)
    {
        _sqsClient = sqsClient;
        _logger = logger;
        _queueUrl = queueUrl;
        _isFifo = isFifo;

        _messageBatcher = new BatchBlock<Message>(PublishBatchSize, new GroupingDataflowBlockOptions
        {
            BoundedCapacity = 1000
        });

        _processorTask = StartAsync();
    }

    private SendMessageBatchRequestEntry CreateBatchRequestEntry(Message message)
    {
        var request = new SendMessageBatchRequestEntry
        {
            Id = message.MessageId,
            MessageBody = message.MessageBody,
            MessageAttributes =
            {
                ["MessageType"] = new MessageAttributeValue
                {
                    DataType = "String",
                    StringValue = message.MessageType
                }
            }
        };

        if (_isFifo)
        {
            request.MessageGroupId = message.GroupId;
            request.MessageDeduplicationId = message.MessageId;
        }

        return request;
    }

    private async Task StartAsync()
    {
        while (!_messageBatcher.Completion.IsCompleted)
        {
            var batch = (await _messageBatcher.ReceiveAsync().ConfigureAwait(false))
                .Select(CreateBatchRequestEntry)
                .ToList();

            _logger.LogDebug($"Publishing {PublishBatchSize} messages...");

            var messageIds = string.Join(", ", batch.Select(r => r.Id));

            try
            {
                var batchResponse = await _sqsClient.SendMessageBatchAsync(_queueUrl,batch);

                if (batchResponse.Failed.Any())
                {
                    var errors = string.Join(", ", batchResponse.Failed.Select(f => f.Message));
                    throw new MigrationException(
                        $"Failed to publish batch of messages with IDs {messageIds}: {errors}");
                }

                _logger.LogDebug($"Published batch of messages with IDs {messageIds}");
            }
            catch (AmazonServiceException ex)
            {
                throw new MigrationException(
                    $"Failed to publish batch of messages with IDs {messageIds}.", ex);
            }
        }
    }

    public void PublishMessages(params Message[] messages)
    {
        foreach (var message in messages)
        {
            _messageBatcher.Post(message);
        }
    }

    public void Dispose()
    {
        _messageBatcher.TriggerBatch();
        _messageBatcher.Complete();
        _processorTask.Wait();
        _processorTask.Dispose();
        _sqsClient.Dispose();
    }
}


texts: Search table without repetitive for loops

texts:
I have an astropy table with a column containing datetime.datetime instances. I want to isolate the rows of this table that correspond to a user specified year, month, day, or hour. The table I am working with has a little over 100,000 entries, but as a more manageable example you can consider the following table with only six entries:

data = [1, 2, 3, 4, 5, 6]
dates = [datetime.datetime(2010, 6, 25, 0, 15),
         datetime.datetime(2011, 5, 25, 0, 45),
         datetime.datetime(2011, 6, 25, 1, 15),
         datetime.datetime(2012, 7, 12, 3, 45),
         datetime.datetime(2013, 9, 15, 2, 15),
         datetime.datetime(2014, 2, 25, 2, 45)]

test_tab = Table(data=[dates, data], names=['date', 'data'])

To search this table I came up with the following function:

import numpy as np
def search(year=None, month=None, day=None, hour=None):

    indx = [True for i in test_tab['date']]
    if year:
        test_func = np.vectorize(lambda x: x.year == year)
        indx = np.logical_and(indx, test_func(test_tab['date']))

    if month:
        test_func = np.vectorize(lambda x: x.month == month)
        indx = np.logical_and(indx, test_func(test_tab['date']))

    if day:
        test_func = np.vectorize(lambda x: x.day == day)
        indx = np.logical_and(indx, test_func(test_tab['date']))

    if hour:
        test_func = np.vectorize(lambda x: x.hour == hour)
        indx = np.logical_and(indx, test_func(test_tab['date']))

    return test_tab[np.where(indx)[0]]

My problem is that this function executes 4 loops over the same table. Is it possible to accomplish the same thing more efficiently?


texts: Add item at the beginning of each inner array in jagged array

texts:
So, there is a big jagged string array (~ [120] [1 000 000]) here that represents data from an excel worksheet ( columns / rows).

Task: We have to append items at the beginning of each inner array.

I have a solution, but I am not sure about performance.

private string[][] AddField(string[][] exportDataFieldValues, string linkDisplayFieldValue)
    {
        var newExportDataFieldValues = new List<string[]>();
        foreach (var row in exportDataFieldValues)
        {
            var cellsRange = row.ToList();
            cellsRange.Insert(0, linkDisplayFieldValue);

            newExportDataFieldValues.Add(cellsRange.ToArray());
        }

        return newExportDataFieldValues.ToArray();
    }

Q: As you can see, my solution contains a lot of type conversions, I believe there is a more effective solution. Сan you provide a more effective solution?


texts: Finding world-writable files in local directories only

texts:
Over at Stack Overflow I asked how to scan a local filesystem ignoring all remote mount points. I only really wanted a push in the right direction and received it. After clacking away on my keyboard I think I might have what I what I need. I ask for an evaluation to determine if it fulfills the requirements:

Scan every local directory for world-writable files ignoring "special" directories (/sys, /proc, /dev)
Ignore directories
Ignore files on any remote filesystems which may be mounted
Ignore any files in an "exclude" list

I'm quite certain it could be drastically optimized and any suggestions are welcome as are any suggestions for a better algorithm. However, rewriting the script is secondary to performing the task properly.

I've tested it and I'm fairly confident that I've created what I want. I just need some extra eyes to confirm.

#!/usr/bin/perl

# Directives which establish our execution environment
use warnings;
use strict;
use Fcntl ':mode';
use File::Find;
no warnings 'File::Find';
no warnings 'uninitialized';

# Variables used throughout the script
my $DIR = "/var/log/tivoli/";
my $MTAB = "/etc/mtab";
my $PERMFILE = "world_writable_w_files.txt";
my $TMPFILE = "world_writable_files.tmp";
my $EXCLUDE = "/usr/local/etc/world_writable_excludes.txt";
my $ROOT = "/";
my @devNum;

# Create an array of the file stats for "/"
my @rootStats = stat("${ROOT}");

# Compile a list of mountpoints that need to be scanned
my @mounts;

open MT, "<${MTAB}" or die "Cannot open ${MTAB}, $!";

# We only want the local mountpoints
while (<MT>) {
  if ($_ =~ /ext[34]/) {
    my @line = split;
    push(@mounts, $line[1]);

  }

}

close MT;

# Read in the list of excluded files and create a regex from them
my $regExcld = do {
  open XCLD, "<${EXCLUDE}" or die "Cannot open ${EXCLUDE}, $!\n";
  my @ignore = <XCLD>;
  chomp @ignore;
  local $" = '|';
  qr/@ignore/;

};

# Create a regex containing mountpoint dev numbers to compare file device numbers to.
my $devRegex = do {
  chomp @devNum;
  local $" = '|';
  qr/@devNum/;

};

# Create the output file path if it doesn't already exist.
mkdir("${DIR}" or die "Cannot execute mkdir on ${DIR}, $!") unless (-d "${DIR}");

# Create our filehandle for writing our findings
open WWFILE, ">${DIR}${TMPFILE}" or die "Cannot open ${DIR}${TMPFILE}, $!";

foreach (@mounts) {
  # The anonymous subroutine which is executed by File::Find
  find sub {
    # Is it in a basic (non-special) directory, ...
    return if $File::Find::dir =~ /sys|proc|dev/;

    # ...a regular file, ...
    return unless -f;

    # ...local, ...
    my @dirStats = stat($File::Find::name);
    return unless $dirStats[0] =~ $devRegex;

    # ...and world writable?
    return unless (((stat)[2] & S_IWUSR) && ((stat)[2] & S_IWGRP) && ((stat)[2] & S_IWOTH));

    # Add the file to the list of found world writable files unless it is
    # in the list if exclusions
    print(WWFILE, "$File::Find::name\n") unless ($File::Find::name =~ $regExcld);

  }, $_;

}

close WWFILE;

# If no world-writable files have been found ${TMPFILE} should be zero-size;
# Delete it so Tivoli won't alert
if (-z "${DIR}${TMPFILE}") {
  unlink "${DIR}${TMPFILE}";

} else {
  rename("${DIR}${TMPFILE}","${DIR}${PERMFILE}") or die "Cannot rename file ${DIR}${TMPFILE}, $!";

}


texts:
In a TED talk Linus Torvalds made a point about “good taste” at approximately 14:10 in the interview. I read through his examples of “bad taste” and “good taste” and wanted to implement the same principle for a function that deletes the last node in a singly linked list. I also followed his coding style.
#include <stdio.h>
#include <stdlib.h>

/* linked list structure */
struct node {
    int data;
    struct node *next;
};

/* create new node */
struct node *new_node(int data, struct node *next)
{
    struct node *new = malloc(sizeof *new);
    if (!new) {
        fprintf(stderr, "Error: memory allocation failed\n");
        exit(EXIT_FAILURE);
    }
    new->data = data;
    new->next = next;
    return new;
}

/* delete last node */
void delete_last(struct node *head)
{
    if (head == NULL) {
        fprintf(stderr, "Error: linked list underflow\n");
        exit(EXIT_FAILURE);
    }
    struct node **cursor = &head;
    while ((*cursor)->next != NULL)
        cursor = &(*cursor)->next;
    free(*cursor);
    *cursor = NULL;
}


texts:
I came across below interview question and I am working on it:

  Build a queue class with the enqueue and dequeue methods. The queue
  can store an UNLIMITED number of elements but you are limited to
  using arrays that can store up to 5 elements max.

Here is what I was able to come up with. Is this the right way to do it in the interview or is there any better way we should implement in the interview?

class Solution {
  private final List<List<Integer>> array;

  public Solution() {
    this.array = new ArrayList<>();
  }

  public void enqueue(int value) {
    if(array.isEmpty()) {
      List<Integer> arr = new ArrayList<>();
      arr.add(value);
      array.add(arr);
      return;
    }
    if(array.get(array.size() - 1).size() != 5) {
      array.get(array.size() - 1).add(value);
      return;
    }
    List<Integer> arr = new ArrayList<>();
    arr.add(value);
    array.add(arr);
    return;
  }

  public int dequeue() {
    if(array.isEmpty()) {
      return -1;
    }
    for(List<Integer> l : array) {
      for(int i=0; i<l.size(); i++) {
        return l.remove(i);
      }
    }
    return -1;
  }
}


texts:
I made a small Popup component to show different error/success...etc. messages.

Template:

<div [@visibilityChanged]="isVisible" *ngIf="shouldShow" [ngClass]="messageType">
    <ng-content></ng-content>
</div>

Component:

import {
  Component, OnChanges, Input,
  Renderer2, AfterViewInit, ElementRef, AfterViewChecked,
  HostListener
} from '@angular/core';

import { trigger, state, animate, transition, style } from '@angular/animations';

/**
 * This class represents the popup component.
 */
@Component({
  moduleId: module.id,
  selector: 'sd-popup',
  templateUrl: 'popup.component.html',
  styleUrls: ['popup.component.css'],
  animations: [trigger('visibilityChanged', [
    transition(':enter', [
      style({ opacity: 0 }),
      animate(100, style({ opacity: 1 }))
    ]),
    transition(':leave', [
      style({ opacity: 1 }),
      animate(100, style({ opacity: 0 }))
    ])
  ])
  ]
})
export class PopUpComponent implements AfterViewInit, AfterViewChecked {
  @Input() messageType: string | string[];
  @Input() errorState: boolean;
  @Input() parentEl: Element;

  public shouldShow: boolean;

  constructor(private popupEl: ElementRef,
    private renderer: Renderer2) {
  }

  ngAfterViewInit(): void {
    // Append to body for better calculation
    document.body.appendChild(this.popupEl.nativeElement);

    //use random delay for load balancing
    this.renderer.listen(this.parentEl, 'keydown', () => {
      setTimeout(() => {
        this.shouldShow = this.errorState;
      }, this.getRandomInt(1, 50));
    });
  }

  @HostListener('window:resize')
  @HostListener('window:scroll')
  ngAfterViewChecked(): void {
    // calculate position when view checked,window is resized or scrolling
    // consider to use load balancing here as well (random delay might be visible)
    this.calculatePosition(this.popupEl.nativeElement, this.parentEl);
  }

  public calculatePosition(element: any, target: any): void {
    const targetOffset = target.getBoundingClientRect();

    this.renderer.setStyle(element, 'top', `${(targetOffset.top + document.documentElement.scrollTop) - element.offsetHeight - 5}px`);
    this.renderer.setStyle(element, 'left', `${targetOffset.left + (target.offsetWidth / 2 - element.offsetWidth / 2)}px`);
    this.renderer.setStyle(element, 'zindex', `${target.zindex + 100}px`);
  }

  getRandomInt(min: number, max: number) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

}

SCSS:

:host {
    position:absolute;
    opacity: 0.9;
 }

 .errorMessage {
    padding: 0.375rem 0.75rem;
    font-size: 1rem;
    line-height: 1.5;
    color: #fff;
    background-image: none;
    background-clip: padding-box;
    border-radius: 0.25rem;
 }

 .warning {
    @extend .errorMessage;
    background-color: #CD464D;
    border: 1px solid #CD464D;
 }

  .success {
     @extend .errorMessage;
     background-color: rgb(15, 230, 147);
     border: 1px solid rgb(15, 230, 147);
  }

 div:after, div:before {
    top: 100%;
    left: 50%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
}

 div:after {
    border-color: rgba(136, 183, 213, 0);
    border-top-color: inherit;
    border-width: 5px;
    margin-left: -5px;
}
div:before {
    border-color: rgba(194, 225, 245, 0);
    border-top-color: inherit;
    border-width: 6px;
    margin-left: -6px;
}

And finally usage:

<input #passInput type="password" name="password" id="password" class="form-control" formControlName="password"/>
                <sd-popup [parentEl]="passInput" [errorState]="password.errors?.required && (password.dirty || password.touched)"
                    messageType="success">Password is required</sd-popup>

Tell me what do you think about it!


texts: Another even Fibonacci numbers implementation

texts:
This is intended as something of a comparative study. I'm including not just one, but two separate implementations of code to implement the Project Euler problem to sum the even Fibonacci numbers up to 4,000,000. The first is a very C-like implementation. The second attempts to make much more use of modern C++. To do so, it includes a specialized iterator to generate Fibonacci numbers, and a generic algorithm for summing items from a range conditionally (and uses a lambda expression to specify the condition).

If we include that generic algorithm, the latter is (marginally) longer than the former (though I've also included some timing code in the former that's currently absent in the latter). I'm curious to know what people think of them--whether the latter is really an improvement, which style you'd prefer to see in your code base, and so on.

More specific questions:

Do iterators and algorithms produce a net loss or gain for this particular code?
Is it problematic that the iterator's operator != actually does a < comparison internally, on the basis that it's looking for the end of a logical range, but doesn't expect you to necessarily know the exact value of the Fibonacci number at the end of the range you care about?

Version 1:

#include <iostream>
#include <time.h>

int main() {
    clock_t start = clock();
    unsigned long long total;
    int max_reps = 10000;

    for (int reps = 0; reps < max_reps; reps++) {
        total = 0;
        unsigned long long first = 1;
        unsigned long long second = 1;
        unsigned long long fib = first + second;

        while (fib < 4000000) {
            if ((fib % 2) == 0)
                total += fib;
            first = second;
            second = fib;
            fib = first + second;
        }
    }
    clock_t stop = clock();

    std::cout << total
              << "\ntime: "
              << (1000.0 * (stop - start)) / double(CLOCKS_PER_SEC * max_reps) << "ms\n";
}

...and version 2:

#include <iostream>

template <class T=unsigned>
class fib_iterator {
    T first, second;
public:
    fib_iterator(T v1=1, T v2 = 1) : first(v1), second(v2) {}
    int operator *() { return first + second; }
    fib_iterator &operator++() {
        int temp = first + second;
        first = second;
        second = temp;
        return *this;
    }
    bool operator!=(fib_iterator const &r) { return first < r.first; }
};

template <class InIt, class F, class T>
T accumulate_if(InIt b, InIt e, T accum, F f) {
    while (b != e) {
        if (f(*b))
            accum += *b;
        ++b;
    }
    return accum;
}

int main() {
    std::cout << accumulate_if(fib_iterator<>(), fib_iterator<>(4000000),
        0U, [](unsigned v) { return v % 2 == 0; });
}

Of course, the questions I've asked above are not intended to limit the scope of reviews--only to add to the normal review I'd hope for when posting any code here.


texts: Update database, refresh the page to show changes, show a success message

texts:
Follow up question for:

Update database, reload page then show a success message

I have a table of articles, in each row is a button to activate / deactivate the article, along with other actions shown here:

The problem I was having:

If I did a standard AJAX call, I could append a success message to a div but it would not refresh the page.  That's where document.location.reload(true); comes in, but now the page refreshes before the success message can show.  Sure you could setTimeOut, but it seems a bit backwards to show a success message before you can see the result, so on to my method.

Note: All I/O is filtered with a function which I chose to leave out for ease of reading and error handling has not yet been implemented

The Ajax in articlelist.php:

This will post the data to articlecontrol.php to be processed, I've added a selector here because the controller also handles other requests i.e. Categories.

// ACTIVATE / DEACTIVATE WITH LINK
$(document).on("click",".active_button",function() {

    var articleID = $(this).attr("name");
    var active = $(this).val();
    var selector = $("#selector").attr("name");

    $.ajax({
    type: "POST",
    url: "controllers/articlecontrol.php",
    data: { articleID: articleID, active:active, selector: selector },
    success: function(data){
        document.location.reload(true);
    }
    });
});

I'll use the activate / deactivate PHP as the example in articlecontrol.php

If the database updated set the success info in $_SESSION['status'] ready for output on our table page:

if(isset($_POST['selector'])) {
    $selector = $_POST['selector'];

// ACTIVATE / DEACTIVATE ARTICLE w/Button
if(isset($_POST['active']) && $selector === 'article') {
        $where = array('article_id' => $_POST['articleID']);

        $active = ($_POST['active'] == 'YES') ? '0' : '1';

        $update = array('article_active' => $active);

    if ($database->update('wcx_articles', $update, $where)) {
        if ($active == '0') {
            $_SESSION['status'] = '
Article Deactivated Successfully
';
        } else {
            $_SESSION['status'] = '
Article Activated Successfully
';
        }
    }
}

This is how I'm showing the success message in articlelist.php:

<?php
if(isset($_SESSION['status'])) {
    echo $_SESSION['status'];
    $_SESSION['status'] = '';
}
?>

I'm also checking if there is anything in the .successmessage div on page load and fading it out:

 $(document).ready(function(){
   if ($(".successmessage").html().length > 0) {
       $('.successmessage').fadeOut(3000);
   }
 });


texts:
I found myself having to implement Bresenham's line drawing algorithm.

I'm looking for feedback on effectivity and code style. Can I reduce the code somehow?

template<typename Callable>
void bresenham(Vec2i p0, Vec2i p1, Callable&& cb){
    const auto swap_xy = std::abs(p1.y - p0.y) > std::abs(p1.x - p0.x);
    if (swap_xy) {
        swap(p0.x, p0.y);
        swap(p1.x, p1.y);
    }

    auto mark = [swap_xy, &cb](Vec2i p) {
        if (swap_xy) {
            cb(Vec2i (p.y, p.x));
        }
        else {
            cb(p);
        }
    };

    const auto d = p1 - p0;
    const auto dx_abs = std::abs(d.x);
    const auto step_y = d.y < 0 ? -1 : 1;
    const auto step_x = d.x < 0 ? -1 : 1;
    auto pen = p0;
    while (pen.x != p1.x) {
        bool skip = false;
        auto error = std::abs(2 * d.y*(pen.x - p0.x) - 2 * d.x*(pen.y - p0.y));
        while (error > dx_abs) {
            pen.y += step_y;
            error -= 2 * dx_abs;
            mark(pen);
            skip = true;
        }
        if (!skip) {
            mark(pen);
        }
        pen.x += step_x;
    }
    mark(p1);
}

The class Vec2i is the equivalent of:

struct Vec2i{
   Vec2i(int ax = 0, int ay = 0) : x(ax), y(ay) {}
   int x,y;
};

with the expected copy constructor and arithmetic operators that one usually associates with a mathematical vector.

I have unit tested this extensively and found no issues. Although I'm a bit worried as most implementations I've seen are much longer (2-3x) and have special handling for a lot of cases, cases that just seem to work in my unit tests.

I accept any type of callback that will be called for each produced position. Some times I need to raster the line, some times I just need to iterate along the line and do things. This seemed appropriate to me.


texts: Updating number of votes with a "Like" button

texts:
I have a "Like" button in my iOS app that updates the votes every time it's tapped. Just like Facebook, Instagram, ProductHunt, etc.

I have a custom cell where that IBAction and IBOutlet is declared and that's where I'm making the query to the Parse db to update the UI (initially I'm querying the vote values from the other file from the cellForRowAtIndexPath.) In the custom cell file, I also created a delegate method, with a Protocol type that I'm accessing in my TableViewController in the cellForRowAtIndexPath.

I'm a bit of a newbie and studying the MVC data structure (assuming that's the biggest issue here), so please be easy on me!

Here is the code in the custom cell:

protocol CellButtonDelegate {

    func buttonClicked(cell : PFTableViewCell)

}
var delegate : CellButtonDelegate?

class FeedTableViewCell: PFTableViewCell {

    var delegate : CellButtonDelegate?

    var parseObject:PFObject?

    internal var buttonEnabled : Bool? {

        get {

            return loveOutlet.enabled

        } set {

            loveOutlet.enabled = newValue!
        }
    }

 @IBAction func loveButton(sender: AnyObject) {

        if(parseObject != nil) {

            if var votes: Int? = parseObject!.objectForKey("votes") as? Int {
                votes!++

                parseObject!.setObject(votes!, forKey: "votes")
                parseObject!.saveInBackground()

                print(votes!)
            }

            delegate?.buttonClicked(self)
        loveOutlet.enabled = false

        }

    }

Here is the code in the cellForRowAtIndexPath:

   override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {

        var cell: FeedTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? FeedTableViewCell

        if(cell == nil) {

            cell = NSBundle.mainBundle().loadNibNamed("FeedTableViewCell", owner: self, options: nil)[0] as? FeedTableViewCell
        }

        objects![indexPath.row]

        if let pfObject = objectArray?[indexPath.row] {
                     cell?.parseObject = object
var votes: Int? = pfObject["votes"] as? Int
            if votes == nil {
                votes = 0
            }

            cell?.delegate = self

            let isEnabled = pfObject["isEnabled"] as! Int
            if isEnabled == 1 {

                cell?.buttonEnabled = true

            } else {

                cell?.buttonEnabled = false

            }

            print(pfObject["isEnabled"] as? Bool)
}

}

func buttonClicked(cell: PFTableViewCell) {

    let indexPath = tableView.indexPathForCell(cell)

    var object : PFObject = objectArray![indexPath!.row] as! PFObject

    object["isEnabled"] = 0
    objectArray?.removeAtIndex((indexPath?.row)!)
    objectArray?.insert(object, atIndex: (indexPath?.row)!)

}

Currently, when the button is tapped, the UI updates, but it also sends a query to the db (the activity indicator/internet indicator at the top right of the iPhone is spinning every time I "like" something).

When I use other apps, like Facebook for example, the query isn't being immediately sent and updated, it does it at a later point (don't understand when or how; can't figure that out but it does seem more efficient).

Lastly, sometimes an individual cell updates, and on other (awful) days the vote appears for every 3rd cell. Trying to figure this out for days.

In summary: ultimately, I want to optimize the query for voting in an iOS app. How do Facebook, Instagram and everyone else do it so smoothly?


texts: Adding columns in Spark dataframe based on rules

texts:
I have a dataframe df, which contains below data:

**customers**   **product**   **Val_id**
     1               A            1
     2               B            X
     3               C
     4               D            Z

i have been provided 2 rules, which are as below:

**rule_id**   **rule_name**  **product value**  **priority**
   123              ABC             A,B               1
   456              DEF             A,B,D             2

Requirement is to apply these rules on dataframe df in priority order, customers who have passed rule 1, should not be considered for rule 2 and in final dataframe add two more columns rule_id and rule_name, i have written below code to achieve it:

val rule_name = when(col("product").isin("A","B"), "ABC").otherwise(when(col("product").isin("A","B","D"), "DEF").otherwise(""))
val rule_id = when(col("product").isin("A","B"), "123").otherwise(when(col("product").isin("A","B","D"), "456").otherwise(""))
val df1 = df_customers.withColumn("rule_name" , rule_name).withColumn("rule_id" , rule_id)
df1.show()

Final output looks like below:

**customers**   **product**   **Val_id**  **rule_name**  **rule_id**
     1               A            1           ABC            123
     2               B            X           ABC            123
     3               C
     4               D            Z           DEF            456

Is there any better way to achieve it, adding both columns by just going though entire dataset once instead of going through entire dataset twice?


texts: Most performant way to check if elements are overlapping

texts:
I know you can calculate if an element is overlapping another by comparing the top|bottom|right|left properties within the getBoundingClientRect method. However, you need to loop through the elements to do so. I'm curious to know what is the performant way of checking to see if an element is overlapping any other element. For example, checking to see if label one is overlaying any other element. Then checking to see if label two is overlapping any other element including label one without using a loop each time, or is this the only way? Currently I'm just checking one element against the previous.

// dismiss -- just creating less CSS
const randomColor = "#" + ((1 << 24) * Math.random() | 0).toString(16);
document.querySelectorAll('.label').forEach((x, i) => {
  document.querySelectorAll('.label')[i].style.background = "#" + ((1 << 24) * Math.random() | 0).toString(16);
});

//function to check for overlapping
function overlayCheck() {
  let points = document.querySelectorAll('.label');
  let rightPos = (elem) => elem.getBoundingClientRect().right;
  let leftPos = (elem) => elem.getBoundingClientRect().left;
  let topPos = (elem) => elem.getBoundingClientRect().top;
  let btmPos = (elem) => elem.getBoundingClientRect().bottom;

  for (let i = 1; i < points.length; i++) {
    if (!(
        rightPos(points[i]) < leftPos(points[i - 1]) ||
        leftPos(points[i]) > rightPos(points[i - 1]) ||
        btmPos(points[i]) < topPos(points[i - 1]) ||
        topPos(points[i]) > btmPos(points[i - 1])
      )) {
      points[i].innerHTML = `${points[i].innerHTML} C`;
    }
    if (i === points.length - 1) {
      return
    }
  }
}

overlayCheck();
.parent {
  position: relative;
  display: flex;
}

.label {
  height: 75px;
  left: 0;
  width: 100px;
  margin-left: 10px;
  background-color: orange
}

.cover {
  width: 220px;
  position: absolute;
  left: 0;
  height: 50px;
  bottom: 0;
}

Label 1

Label 2

Label 3

Label 4

Label 5

Label 6


texts: URL-safe pseudorandom string generator in C#

texts:
public static class SimpleToken
{
    const string TOKENALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.";
    static string NewToken(int length = 16)
    {
        var rnd = new RNGCryptoServiceProvider();
        var tokenBytes = new byte[length];
        rnd.GetBytes(tokenBytes);
        var token =
            Enumerable
                .Range(0, length)
                .Select(i => TOKENALPHABET[tokenBytes[i] % TOKENALPHABET.Length])
                .ToArray();

        return new String(token);
    }
}

I needed a quick and dirty(?) way to generate long urls for onetime use. It's a simple login-scheme where a user enters his e-mail and gets a one-time URL for logging in. The URL is discarded after one use.

I.e. http://example.com/tokenlogin/3cuzLkh8GcANjqnWcijEeJIHphHx6ZDwfj-2XTR4bfkkqmzmmFYAY2tWsZWST1.5


texts:
I needed to find whether any image's width at or higher than a certain directory folder exceeds a limit.  Is this code a good way of doing this, or is there a way in which it can be improved?  I ran it over at least a couple hundred images and several hundred other files contained in the main directory (not C:\Users, but I don't want to show my user name), and it completed so fast the time is irrelevant.

public static void Main()
{
    string[] files = Directory.GetFiles("C:\\Users", "*.png", SearchOption.AllDirectories);

    foreach (string file in files)
    {
        Image img = Image.FromFile(file);

        if (img.Width > 1100)
        {
            Console.WriteLine(file);
            Console.WriteLine(img.Width);
        }

        img.Dispose();
    }
}


texts:
Can someone please evaluate my code and let me know how I can improve it?

public class ArrayListImplementation {

static class ListNode<T> {
    private T value;

    public ListNode(T val) {
        this.value = val;
    }

    public T getValue() {
        return this.value;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(this.value);
        return sb.toString();
    }
}

static class List<T> {
    private ListNode<T>[] node;
    private int listSize;
    private int initialCapacity;

    public List(int size) {
        node = new ListNode[size];
        initialCapacity = size;
    }

    public int size() {
        return listSize;
    }

    public boolean isEmpty() {
        return listSize == 0;
    }

    public T get(int index) {
        if(index >= initialCapacity) {
            throw new ArrayIndexOutOfBoundsException();
        }

        return node[index].getValue();
    }

    public void add(T val) {
        if(listSize == initialCapacity) {
            System.out.println("No space to add a new list element");
            return;
        }

        ListNode<T> head = null;
        if(listSize == 0) {
            head = new ListNode<>(val);
            node[0] = head;
            listSize++;
            return;
        }

        ListNode<T> cur = new ListNode<>(val);
        node[listSize++] = cur;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[ ");
        for(int i = 0; i < initialCapacity - 1; ++i) {
            sb.append(node[i].getValue() + ", ");
        }
        sb.append(node[initialCapacity - 1].getValue() + " ]");
        return sb.toString();
    }

    public void clear() {
        node = new ListNode[initialCapacity];
        listSize = 0;
        return;
    }

    public boolean remove(T value) {
        boolean result = false;
        for(int i = 0; i < initialCapacity; ++i) {
            if(node[i].getValue() == value) {
                result =  remove(node[i], i);
                if(result) {
                    listSize--;
                }
            }
        }
        return result;
    }

    private boolean remove(ListNode<T> toBeRemoved, int index) {
        if(index < 0 || index >= initialCapacity) {
            return false;
        }

        if(initialCapacity > 1) {
            int prevSize = initialCapacity;
            ListNode<T>[] copyNode = node;

            node = new ListNode[--initialCapacity];
            for(int i = 0; i < index; ++i) {
                node[i] = copyNode[i];
            }

            for(int i = index + 1; i < prevSize; ++i) {
                node[i-1] = copyNode[i];
            }
        }
        else {
            this.clear();
        }
        return true;
    }
}

public static void main(String[] args) {
    List<Integer> list = new List<Integer>(5);
    System.out.println(list.isEmpty());
    list.add(5);
    list.add(10);
    list.add(15);
    System.out.println(list.get(0));
    System.out.println(list.get(2));
    System.out.println(list.size());
    list.add(20);
    System.out.println(list.size());
    list.add(25);
    System.out.println(list.get(4));
    System.out.println(list.remove(20));
    System.out.println(list.remove(45));
    System.out.println(list.remove(5));
    System.out.println(list.remove(25));
    System.out.println(list.remove(10));
    System.out.println(list.remove(15));
    //System.out.println(list.get(5)); //ArrayIndexOutOfBoundsException
    list.clear();
    System.out.println(list.size());
}}


texts:
This is my code to chmod all .htaccess files under all website dirs under public_html dir.

The reason I use this code is to make sure WordPress plugins won't "freak out" and change my .htaccess file undesirably.

This is a shared server environment so I can't access htppd.conf instead, and must edit the different .htaccess files per each site, with the below code:

for dir in "$HOME"/public_html/*.{com,co.il}/; do
  if pushd "$dir"; then
    chmod 644 .htaccess
    popd
  fi
done 2>/dev/null


texts:
I made a small program that tests numbers against some properties:

Welcome to Numbers!
Is it odd? 4
No
Is it a multiple of 18? 38
No
Is it big? 100
Yes

That's basically it :)

My code is:

import System.IO
import Text.Read

askUser :: String -> IO Double
askUser str = do
  putStr str
  num <- fmap readMaybe getLine

  case num of
    Nothing -> putStrLn "That is not a number!" >> askUser str
    Just num -> return num

numberCheck :: [Double] -> String -> IO ()
numberCheck list text = do
  num <- askUser ("Is it " ++ text ++ "? ")

  if num `elem` list
    then putStrLn "Yes"
    else putStrLn "No"

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  putStrLn "Welcome to Numbers!"
  let alot = 99999

  let oddNum = take alot [x | x <- [0..], odd (round x)]
  numberCheck oddNum "odd"

  let multiples18 = take alot [x | x <- [0..], round x `mod` 18 == 0]
  numberCheck multiples18 "a multiple of 18"

  let bigNumbers = take alot [99..]
  numberCheck bigNumbers "big"

Is there anything that can be improved? I was especially thinking of the alot number, as it is not a "clean" way of solving this. But if I don't, Haskell will continue checking the list infinitely.

Is there any nicer way of achieving this?

Note: I used lists instead of comparisons because that's what I just learned, and so you can ignore me using lists if you want to :)


texts: Directory tree representation with double linked list

texts:
var root = this;
root.node = function(path, type) {
  root.type = type;
  this.type = type;
   this.parents = [];
   this.children = [];
   var components = path.split('/');
   this.parents = parseParents(components);
   this.name = components[components.length - 1];
   this.addChild = function(path, type){
              if(this.type === 'file'){
                throw new Error('A file node cannot have any children');
              }
              this.children.push(new root.node(path, type));
  }

  function parseParents(components){

        var parents = [];
        if(components.length > 0){
           for(var i = (components.length - 1); i > 0; i--){
              if(components[i] !== "")
                if(parents.length === 0){
                  var currentParent = new node(components[i], 'dir');
                  currentParent.children.push(new node(components[0], root.type));
                  parents.push(currentParent);
                }
                else{
                  var newParent = new node(components[i], 'dir');
                  var curretnChild = new node(components[i - 1], 'dir');
                  currentParent.parents.push(newParent);
                  currentParent = newParent;
                }
           }
           return parents;
         }
         return [];

   }
   return this;
}

var a = new node('/usr/local/foo', 'dir');
a.addChild('test', 'file');
console.log(a);

2 way linked list, works great besides that the the 'leaf' items are not populated currently, since in the current structure it will result in an infinite loop.

You thoughts please.


texts:
I know this is kind of stuff is somewhat done to death but please still try to review it fairly.

My code will only go within the interval of [1,9]

def guessing_game():
    no_of_guess = 0
    c = "y"
    import random
    a = random.randint(1,9)
    while c == "y":
        b = input("Enter a guess: ")
        if b.isdigit():
            if int(b) == a:
                c = input("You got it! Play again? Enter \"Y\" if yes, and anything else to exit. ").lower()
                no_of_guess +=1
                a = random.randint(1,9)
            elif int(b) > a:
                c = input("Too high. Try again? Enter \"Y\" if yes, and anything else to exit. ").lower()
                no_of_guess +=1
            else:
                c = input("Too small. Try again? Enter \"Y\" if yes, and anything else to exit. ").lower()
                no_of_guess +=1
        else:
            c = input("Haha. Try again? Enter \"Y\" if yes, and anything else to exit. ").lower()
    if c != "y":
        print("How unfortunate. Well, you made %s guess(es)."%no_of_guess)

guessing_game()


texts: Python: Parse string of bracketed list items into list of strings

texts:
I have a string containing several items listed in the following notation:
myString = '[A][B][C]'

And I would like to parse that to a python list of several strings:
['A', 'B', 'C']

I know this can be solved with:
myString = myString.lstrip('[')
myString = myString.rstrip(']')
myList = myString.split('][')

I'd just like to know if there is an even more pythonic way of doing it.
Compare https://stackoverflow.com/a/1653143/10983441 where the most elegant way in the end was to use pyparsing with nestedExpr.


texts: Made a monster array for a text based game with a class constructor C++

texts:
I created a class in a separate .h and .cpp file with the idea of having an array of 3 monsters with each monster having different stats( name; health; damage). The problem is that the constructor should change the properties but when I try to call them in the main file only the 3rd monster's properties are changed.
main.cpp
#include <string>
#include <iostream>
#include <Windows.h>
#include <stdio.h>
using namespace std;

#include "Player.h"
#include "Monsters.h"
#include "MonsterCluster.h"

int main()
{

    Player player;
    Monsters monster;
    MonsterCluster enemies;

    enemies = MonsterCluster(0, "Goblin", 20, 5);
    enemies = MonsterCluster(1, "Wraith", 50, 10);
    enemies = MonsterCluster(2, "Legionare", 80, rand() % 60+20);

    cout << enemies.monsterList[2].name << endl;
}

MonsterCluster.h
#pragma once
#include "Monsters.h"

class MonsterCluster :
    public Monsters
{
public:
    Monsters monsterList[3];

    MonsterCluster();
    MonsterCluster(int _monsterIndex, string _name, int _health, int _damage);

}

MonsterCluster.cpp
MonsterCluster::MonsterCluster()
{
    /*name = "";
    health = 2;
    damage = 3;*/
}

MonsterCluster::MonsterCluster(int _monsterIndex, string _name, int _health, int _damage)
{
    monsterList[_monsterIndex].name = _name;
    monsterList[_monsterIndex].health = _health;
    monsterList[_monsterIndex].damage = _damage;
}


texts:
I'm trying to reproduce a gbm model which was estimated without a set.seed value. To do so I need to determine what seed was used, which I can figure out based on one of the summary metrics from the estimated model (as shown below).

require(MatchIt)
require(gbm)
data("lalonde")
i <- 1
while(!(tmp$rel.inf[1] == 82.3429390)){
          gps <- gbm(treat ~ age + educ + nodegree + re74 + re75,
                     distribution = "bernoulli",
                     data = lalonde, n.trees = 100,
                     interaction.depth = 4,
                     train.fraction = 0.8, shrinkage=0.0005,
                     set.seed(i))
          tmp <- summary(gps, plotit=F)
          cat(i,"\n")
          i <- i + 1
}

I think it would be very helpful both for this specific use case and for general future reference to know of any more efficient way of carrying this out. A multicore solution might be a good way to go; I'm researching that myself now. Or perhaps there's a way to improve it by using apply?


texts:
I've been working on a custom malloc where the test code is the following.

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include "../tst.h"
#include "../brk.h"
#include <time.h>
/* returns an array of arrays of char*, all of which NULL */
char ***alloc_matrix(unsigned rows, unsigned columns) {
    char ***matrix = malloc(rows * sizeof(char **));
    unsigned row = 0;
    unsigned column = 0;
    if (!matrix) abort();

    for (row = 0; row < rows; row++) {
        matrix[row] = calloc(columns, sizeof(char *));
        if (!matrix[row]) abort();
        for (column = 0; column < columns; column++) {
            matrix[row][column] = NULL;
        }
    }
    return matrix;
}

/* deallocates an array of arrays of char*, calling free() on each */
void free_matrix(char ***matrix, unsigned rows, unsigned columns) {
    unsigned row = 0;
    unsigned column = 0;
    for (row = 0; row < rows; row++) {
        for (column = 0; column < columns; column++) {
            /*    printf("column %d row %d\n", column, row);*/
            free(matrix[row][column]);
        }
        free(matrix[row]);
    }
    free(matrix);
}

int main(int agrc, char **argv) {
     int i;
    srand(time(NULL));
    int randomnumber;
    int size = 1024;
    void *p[size];
    for (i = 0; i < size; i++) {
        randomnumber = rand() % 10;
        p[i] = malloc(1024 * 1024 * randomnumber);
    }

    for (i = size-1; i >= 0; i--) {
        free(p[i]);
    }

    int x = 1024;
    char *** matrix = alloc_matrix(x, x);
    free_matrix(matrix, x, x);
    return (0);
}

The code compiles and runs cleanly.

developer@1604:~/proj/openmalloc/overhead$ gcc gigtest.c
developer@1604:~/proj/openmalloc/overhead$ ./a.out

But how can I improve it? I would like to make it easier to test the thing (my next work should be to add multithreading to the malloc implementation).

Should I use a testing framework instead?


texts:
As a beginner I'd like to get any kind of feedback. The more the better. Any optimization and style mistakes?

class Account
      attr_reader :name, :balance

      def initialize(name, balance=100)
        @name = name
        @balance = balance
      end

      private

      def pin
      @pin = 789
      end

      def pin_check
        puts "Welcome to the banking system, #{@name}!\n" + "To access your account, input PIN please"
        @input_pin = gets.chomp.to_i
      end

     def pin_error
        return "Access denied: incorrect PIN."
     end

    public

      def access
        if pin_check == pin
          puts "Input d: to deposit money, s: to show balance or w: to withdraw money"
          action = gets.chomp.downcase
            case action
            when "d"
            deposit
            when "s"
            display_balance
            when "w"
           withdraw
            else
        puts "Try again"
          end
        else puts pin_error
        end
      end

      def amount
        puts "Input the amount"
        @money = gets.to_i
      end

      def over_error
        print "You don't own that kind of money, dude! Your balance: $#{@balance}"
      end

      def deposit
       @balance += amount
        puts "Deposited: $#{@money}. Updated balance: $#{@balance}."
      end

      def display_balance
        puts "Balance: $#{@balance}."
      end

      def withdraw
        if  amount <= @balance
          @balance -= @money
           puts "Withdrew: $#{@money}. Updated balance: $#{@balance}."
        else
            puts over_error
        end
      end
    end

    checking_account = Account.new("James Bond", 520_000)
    checking_account.access


texts: Reduce sample rate of GPS data based on distance between points

texts:
The algorithm needs to reduce an RDD[GPSRecord] based on the distance between several points, e.g. "give me only GPS records when the distance between them exceeds 15m".

Right now the algorithm is not interpolating points. It collects a point if it detects that the next value has a distance between it and the last point collected greater than the distance samplePeriod provided.

I'm new to both Scala and Spark so I would like to know if there's a better way to achieve this.

def filterByDistance(gpsRecords:RDD[GPSRecord], distanceSamplePeriod:Int ):RDD[GPSRecord] = {
    val firstGPSRecord = gpsRecords.first()
    val firstRecord: (Double, GPSRecord) = (0, firstGPSRecord)

    // Calculate distance between each point and the next one
    val slidedRecords = RDDFunctions.fromRDD(gpsRecords)
        .sliding(2)
        .map(gpsRecords => {
            (
                utils.getDistanceBetweenPoints(
                    (gpsRecords(0).latitude, gpsRecords(0).longitude),
                    (gpsRecords(1).latitude, gpsRecords(1).longitude)
                ),
                gpsRecords
            )
        })

    // Per partition, for each record calculate the distance traveled relative to the partition starting point
    val partitionRelativeRecords = slidedRecords.mapPartitions(recordsWithDistanceIterator => {
        var distance: Double = 0

        recordsWithDistanceIterator.map(recordsWithDistanceTuple => {
            val accumulatedDistance = recordsWithDistanceTuple._1 + distance
            distance = recordsWithDistanceTuple._1 + distance

            (
                accumulatedDistance,
                recordsWithDistanceTuple._2(1)
            )
        })
    })

    // Get total distance of each partition
    val lastValues = partitionRelativeRecords.mapPartitions(recordIterator => {
        var records: (Double, GPSRecord) = null
        while ( recordIterator.hasNext ) {
            records = recordIterator.next
        }

        Iterator.single(records._1)
    }).collect()

    // Per partition, for each record sum the distance traveled on previous partitions
    var recordsWithDistance = partitionRelativeRecords.mapPartitionsWithIndex((partition, partitionRelativeRecords) => {
        var accumulatedDistance: Double = 0
        for ( i <- 0 until partition ) {
            accumulatedDistance += lastValues(i)
        }

        partitionRelativeRecords.map(partitionRelativeRecord => {
            (
                partitionRelativeRecord._1 + accumulatedDistance,
                partitionRelativeRecord._2
            )
        })
    }, preservesPartitioning = true)

    // Due to the sliding the first record was lost, add it again
    recordsWithDistance = context.parallelize(Array(firstRecord), 1).union(recordsWithDistance)

    // Slide the records again to have the distance of the current record and the next one
    val slidedRecordArrays = RDDFunctions.fromRDD(recordsWithDistance).sliding(2)

    // Compare both distances to see if divided by the requested distanceSamplePeriod the next point exceeds the threshold
    // and collect the next point (no interpolation for now...)
    recordsWithDistance = slidedRecordArrays.map(recordArrays => {
        if ( Math.floor(recordArrays(1)._1 / distanceSamplePeriod) > Math.floor(recordArrays(0)._1 / distanceSamplePeriod) ) recordArrays(1)
        else null
    }).filter(_ != null)

    // The second sliding removed the first element again, add it
    recordsWithDistance = context.parallelize(Array(firstRecord), 1).union(recordsWithDistance)

    // Return only the GPSRecord
    recordsWithDistance.map(_._2)
}


texts: Simple class for 2D  1D array index conversion

texts:
I made a class to convert the index between 2D and 1D arrays.
For example,
between

{1,3,5,7,9,11} and {{1,3},{5,7},{9,11}}

When i is 0, xy should be (0,0)
When i is 1, xy should be (0,1)
When i is 2, xy should be (1,0)

And so on...

I would be able to convert between the i-index and the xy-index to find get the equivalent location. I feel like this piece of code may be too long for its purpose.

class IndexConv {
    public:
    IndexConv(int rows, int cols);
    bool check_i(int i) const;
    bool check_xy(int x, int y) const;
    pair<int, int> to_xy(int i) const;
    int to_i(int x, int y) const;
    private:
    const int rows_;
    const int cols_;
};

IndexConv::IndexConv(int rows, int cols)
    :rows_(rows), cols_(cols) {}

bool IndexConv::check_i(int i) const
{
    return i>=0 || i<rows_*cols_;
}

bool IndexConv::check_xy(int x, int y) const
{
    return x>=0 && y>=0 && x<rows_ && y<cols_;
}
pair<int, int> IndexConv::to_xy(int i) const
{
    if(!check_i(i)) throw out_of_range("IndexConv: i out of bounds.");
    int x = i/cols_;
    int y = i-x*cols_;
    return make_pair(x,y);
}

int IndexConv::to_i(int x, int y) const
{
    if(!check_xy(x,y)) throw out_of_range("IndexConv: xy out of bounds.");
    int i = x*cols_+ y;
    return  i;
}


texts:
I am working on a C#.Net application that will generate an Excel report from a template.  Although the code's not in the app yet, it will pull data from a SQL Server database to populate the report.

I am asking for help in reviewing my class design.  My code is below, with some details of the functions removed for simplicity (if someone feels like they need to see them in order to help, I can add them).

using System;

namespace RGBBProgramSummary
{

class Program
{

    static void Main()
    {
        ReportSheet ProgramSummary = new ReportSheet("Program Summary");

        ProgramSummary.CleanUp();
    }

}
}

using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;

namespace RGBBProgramSummary
{

class ReportBook
{
    public bool Error;
    public DateTime RunDate;
    private string FileName;

    static Application ExcelApp = new Application();
    public Workbooks reportWBs = ExcelApp.Workbooks;
    public Workbook ReportWB;

    public ReportBook()
    {
        RunDate = GetRunDate();
        FileName = GetFileName(RunDate);

        File.Copy(Properties.Settings.Default.Template, FileName);

        ReportWB = reportWBs.Open(FileName);
        //ExcelApp.Visible = true;
    }

    private DateTime GetRunDate()
    {
        ...
        return DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek - 2);
    }

    private String GetFileName(DateTime RunDate)
    {
        string FileName;

        ...
        return Properties.Settings.Default.ReportPath + FileName;
    }

}
}

using System;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;

namespace RGBBProgramSummary
{
class ReportSheet : ReportBook
{
    private Worksheet reportWS;

    public ReportSheet(string SheetName)
    {
        reportWS = ReportWB.Worksheets[SheetName];

        BuildHeader(reportWS);
    }

    public void CleanUp()
    {
        ReportWB.Save();
        ReportWB.Close();

        Marshal.ReleaseComObject(reportWS);
        Marshal.ReleaseComObject(reportWBs);
        Marshal.ReleaseComObject(ReportWB);
    }

    private void BuildHeader(Worksheet WS)
    {

        int WeekColumn = 0;
        int MonthColumn = 0;

        ...
        int j = CountOfWeeks();
        ...
        List<string> MonthList = GetMonthList();
        ...
    }

    private int CountOfWeeks()
    {
        int RunDateWeek
        int FirstDateWeek

        ...
        return RunDateWeek - FirstDateWeek + 1;
    }

    private List<string> GetMonthList()
    {

        List<string> MonthList = new List<string>();

        ...
        return MonthList;
    }

}
}

As you can see, I really only have 2 classes.  ReportBook represents the Workbook itself, and ReportSheet represents the Worksheet (ReportSheet inherits from ReportBook).  I'm wondering if that's overkill, and really if they should be consolidated into one class.  At the least, I would need to make changes if I ever wanted to add an additional worksheet (for one, I wouldn't want to open the workbook in the constructor of the base class then).

Also, I was going create a function in the ReportSheet class to read from the aforementioned SQL DB.  But, after reading answers to another question, I'm thinking that the read from the DB should be in it's own class.


texts: Dependency injection with reading a file

texts:
I implemented this code, looking at a dependency injection program as an example. I wanted to confirm with you all whether this implementation is the right way of doing the same.

namespace TestAsyncProjectWithDI
    {
            public interface IReadFileTypes
            {
                    void ReadUsingFileSteamAsync();
            }
            public class ReadfileFromSystem:   IReadFileTypes
            {
                private readonly StreamReader _reader =null;

                public ReadfileFromSystem(StreamReader reader)
                {
                    _reader = reader;
                }
                public async void ReadUsingFileSteamAsync()
                {
                    await Task.Run(()=> Console.WriteLine("Reading the content of File: {0}", _reader.ReadToEnd()));
                    Console.ReadLine();
                }
          }

        public class Builder
        {
                public  IReadFileTypes ReadFileTypes { get; set; }
                private string path = "C:\\Brackets\\Projects\\index2.html";

                public Builder()
                {
                    ReadFileTypes = new ReadfileFromSystem(new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read)));
                }
        }

        public class Program
        {
                private readonly IReadFileTypes _readFileTypes = null;

                public Program(IReadFileTypes readFileTypes)
                {
                    this._readFileTypes = readFileTypes;
                }
                public void FunctionInvoke()
                {
                    _readFileTypes.ReadUsingFileSteamAsync();
                }
        }

        //starting point of the class
        public class Default
        {
            static void Main(string[] args)
            {
                var build = new Builder();
                var obj = new Program(build.ReadFileTypes);
                obj.FunctionInvoke();
                Console.ReadLine();
            }
        }
    }


texts: Project Euler 40: Champernownes's Constant

texts:
I just finished Project Euler 40 with a brute force method. As usual, any optimizations would be helpful. (I feel like I'm getting better at this scripting thing)

from timeit import default_timer as timer

def product(n):
    from functools import reduce # Valid in Python 2.6+, required in Python 3
    from operator import mul
    return reduce(mul, n, 1)

def find_champernowne_index(d):
    constant = ""
    for k in xrange(1, d + 1):
        constant += str(k)
        if len(constant) >= d:
            return int(constant[d-1])

start = timer()
ans = product(find_champernowne_index(10**x) for x in range(0, 7))
elapsed_time = (timer() - start) * 1000 # s --> ms

print "Found %d in %r ms." % (ans, elapsed_time)


texts:
I was going through the book Hands on Machine Learning With Scikit-Learn & Tensorflow. In one of the chapters, the author mentioned stacking ensemble methods. I tried implementing my own for practice purpose, this is what I have done so far.
from sklearn.base import BaseEstimator, TransformerMixin

class StackClassifier(BaseEstimator, TransformerMixin):

    def __init__(self, estimators=[], blender=None):

        self.estimators = estimators
        self.blender = blender

    def fit(self, X, y=None):
        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2)

        for estimator in self.estimators:
            estimator.fit(X_train, y_train)

        pred_features = np.array([estimator.predict(X_test) for estimator in self.estimators]).T
        self.blender.fit(pred_features, y_test)

    def predict(self, X):
        pred_features = np.array([estimator.predict(X) for estimator in self.estimators]).T
        return self.blender.predict(pred_features)


texts:
I'm working on a data analytics dashboard in Node.js as a portfolio piece. I've built a pipeline that gets the data where it needs to be for more processing, however, I feel the below code can be improved but it overlaps with my inexperience with Node.js and async/await.
The below code looks redundant to my eye. I tried to move the second function into the first in an anonymous async function to no avail, and was wondering if the more experience members here had any suggestions?
async function readFilteredStream() {
    filteredStream = streamConnect(); //Connects to API
    const results = await readStream(filteredStream); //Reads in a sample of data and closes the connection.
    return { data: results };
}

async function respondWithSamples() {
    const results = await readFilteredStream();
    return results;
}


texts: Sierpinski triangle html canvas Implementation

texts:
I wrote my Sierpinski Triangle fractal animation using HTML canvas with JavaScript: JsFiddle
What do you think about it? How I can optimize it, if you see a need for that?
Code:
requestAnimationFrame(update);

const canvas = document.getElementById("c");
const context = canvas.getContext('2d');

var iterations = 0; //how many iterations to perform in current frame, count of fractal func invokes grows exponentially and can be calculated from sum: E 3^k, k = 0 to iterations
const maxIterations = 8; //used when animating, it's better to set 'gradientAnimation' to false, when setting 'maxIterations' to bigger values
const center = { x: canvas.width * 0.5, y: canvas.height * 0.5 };
const halfTriangleSide = 250;

//color animation
const gradientAnimation = true;
var t = 0;
var speed = 0.1;

//division animation
var divideAnim = true;
var divide = true; //loop flag
var mod = 0.0; //color modificator

function drawTriangle(A, B, C)
{
    context.beginPath();
    context.moveTo(A.x, A.y);
    context.lineTo(B.x, B.y);
    context.lineTo(C.x, C.y);
    context.lineTo(A.x, A.y);

    if(gradientAnimation)
    {
        context.fillStyle =
        "rgb(" +
            ((A.x + A.y) * 0.19 * mod) + "," +
            ((B.x + B.y) * 0.15 * mod) + "," +
            ((C.x + C.y) * 0.22 * mod) +
        ")";
    }

    context.fill();
}

function fractal(center, halfSideLen, i)
{
    i++;
    var quaterSide = halfSideLen * 0.5;

    //calc new triangle coords
    var A = {
        x: center.x - quaterSide,
        y: center.y
    };

    var B = {
        x: center.x + quaterSide,
        y: center.y
    };

    var C = {
        x: center.x,
        y: center.y + halfSideLen
    };

    drawTriangle(A, B, C);
    if(i < iterations)
    {
        fractal({x: A.x, y: A.y + quaterSide}, quaterSide, i);
        fractal({x: B.x, y: B.y + quaterSide}, quaterSide, i);
        fractal({x: C.x, y: C.y - (halfSideLen + quaterSide)}, quaterSide, i);
    }
}

function update()
{
    context.clearRect(0, 0, canvas.width, canvas.height);

    //init coords
    var A = {
        x: center.x - halfTriangleSide,
        y: center.y + halfTriangleSide
    };

    var B = {
        x: center.x + halfTriangleSide,
        y: center.y + halfTriangleSide
    };

    var C = {
        x: center.x,
        y: center.y - halfTriangleSide
    };

    context.fillStyle = "#F00";
    drawTriangle(A, B, C);
    context.fillStyle = "#000";

    if(iterations != 0) fractal(center, halfTriangleSide, 0);

    t += speed;
    if(t > Math.PI * 2)
    {
        t = 0;

        if(divideAnim)
        {
            if(iterations == maxIterations) divide = false;
            else if(iterations == 0) divide = true;

            if(divide) iterations++;
            else iterations--;
        }
    }

    if(gradientAnimation)
    {
        mod = 1.25 - Math.sin(t) * 0.5;
    }

    requestAnimationFrame(update);
}


texts:
I'm a C++ beginner and have made a simple class. But I'm not sure if this is well-written. It's basically just a Date class.

#include <iostream>

using namespace std;

class Date{
    int d, m, y;    //Day, Month, Year
public:
    Date(int dd = 1, int mm = 1, int yy = 1);

    int addDay(const int &dd) { d += dd; }
    int addMonth(const int &mm) { m += mm; }
    int addYear(const int &yy) { y += yy; }

    int day() const { return d; }
    int month() const { return m; }
    int year() const { return y; }

    void display() const;   //Print to screen

};

void Date::display() const {
    cout << d << "." << m << "." << y << endl;
}

Date::Date(int dd, int mm, int yy){
    d = dd;
    m = mm;
    y = yy;
}

For example, the arguments of addDay(const int &dd);. Is that good, or should it just be an integer without const and without reference?


texts: HTML and CSS word styling and screen reader usability

texts:
I’m trying to target three words in a h1 for the organization name using  to wrap each word and a unique ID to style each word via css.

It looks like this:

        The
        Community
        Space

However by using span and an ID for each work in the h1, I am causing the screen reader to pause after each word instead of speaking the organization name as a whole. Does anyone have any ideas to solve this issue?


texts: Appending objects to an array based on a field

texts:
I am working with PHP5 (Laravel 5.1), and I couldn't optimize my function, which takes more 4 minutes turning, and fails in the end when I have a huge data (around 6500 rows, but working when i test with around 1000 rows only).
Basically, I try to get an array of objects (which contains users with their balances), and to append it to another array based on depositorId field (by creating a new array for the result).

protected function result(&$items, $statements, $params, $order)
{
    $statements = iterator_to_array($statements);
    $accountTypeId = $this->getAccountTypeId($params);
    $allAccountTypes = $this->getAllAccountTypes($params, $accountTypeId);
    $balancesPerAccount = $this->getAllBalancesPerAccount($allAccountTypes, $order);
    $items = json_decode(json_encode($items), true);
    $appendedResult = [];

    foreach ($statements as $statement) {
       if (!$obj = array_search($statement->depositorId(), array_column($items,'id'))) continue;

       $obj = $items[$obj];

        $obj['className'] = User::class;
        $obj['gamepoints'] = $statement->balance();

        foreach ($allAccountTypes as $accountType) {
            $balancePerDepositor = array_search($obj['id'],
                array_map(function($object) {
                    return $object->depositorId();
                },
                    $balancesPerAccount[$accountType]
                )
            );
            $obj["gamepoints_".$accountType] = isset($balancePerDepositor) ? $balancesPerAccount[$accountTypeId][$balancePerDepositor]->balance(): "";
        }

        array_push($appendedResult,(object)$obj);
    }
}


texts:
I have just coded a Card class which gives a suit, rank and a color to a card. However, I have serious doubts that my code is not well organized and not well structured.

I would like to receive tips on how to improve my code if possible so I can learn from them.

Card class:

import java.util.Random;

public class Card {

    // Setting variables
    String cardSuit, cardRank, cardColor;
    Random generator = new Random();

    // Setting two arrays with the suits and ranks options
    String[] suits = {"hearts", "spades", "diamonds", "clubs"};
    String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8",
    "9", "10", "Jack", "Queen", "King"};

    int randomSuits = generator.nextInt(suits.length);
    int randomRanks = generator.nextInt(ranks.length);

    // Really not sure if I am using the Constructor the right way
     Card() {
         /* Using Random to get a random element from the suits array
            and an random element from the ranks array.
         */
         cardSuit = suits[randomSuits];
         cardRank = ranks[randomRanks];
         // Setting the color of the card in dependence of the suit
         if (cardSuit.equals("hearts") || cardSuit.equals("diamonds")) {
             cardColor = "red";
         }
         else {
             cardColor = "black";
         }
     }

     // Methods to print out the results
     public void getSuit() {
         System.out.println(cardSuit);
     }

     public void getRank() {
         System.out.println(cardRank);
     }

     public void getColor() {
         System.out.println(cardColor);
     }
}

NewCard class:

public class NewCard {
    public static void main(String[] args) {

        // Creating a new Card object
        Card card1 = new Card();
        card1.getSuit();
        card1.getRank();
        card1.getColor();
    }
}


texts:
We have asked to keep the MVC controller as thin, so we decided to move
  all the service calling/business logic into the ViewModel class.

But is it good approach to use a ViewModel class to make a service call?

Does this follows the OOPS/SOLID principle?

public class EmployeeController:Controller
{

  private IEmployeeService EmpServ{get;set;}
  public EmployeeController(IEmployeeService service)
  {
   EmpServ=service;
  }

 public ActionResult GetEmployee(int Id)
 {
  EmployeeViewModel vm=new EmployeeViewModel(EmpServ);
  vm= vm.GetData(Id);
  //some 10 lines of code for validation logic, etc
  return View(vm);
 }

}

The view model class is calling the business service method

public class EmployeeViewModel
{
  public string Name{get;set;}
  //...etc

  private IEmployeeService EmpServ{get;set;}
  public EmployeeViewModel(IEmployeeService service)
  {
   EmpServ=service;
  }

  public EmployeeViewModel GetData(int Id)
  {
   Employee e= EmpServ.GetEmpDetails(id);
   EmployeeViewModel vm=ConvertEmpToViewModel(e);//another helper method
   return vm;
  }
}


texts: Getting the current IP from the command line

texts:
I made a tiny little bash script, that prints the current IP Address to the command line. I checked the script with ShellCheck (0.4.6-1) on a local debian install and I get the following message:

  SC2026: This word is outside of quotes. Did you intend to 'nest '"'single quotes'"' instead'?

What is wrong with the way I have been line-breaking the pipe, or what is proper practice?

#!/bin/bash

 curl -s POST whatismyip.org\
  | grep -A1 'Your IP Address'\
  | awk -F '>' '{print $2}'\
  | sed 's/<\/h2//g'\
  | sed 's/<\/span//g'


texts: producer-consumer Pipeline problem implementation in asyncio

texts:
I wrote this code to make a non-blocking manager along with pipeline operations using asyncio, my main concern is to catch received items producer, and when the received operation is complete. I want to return all together and merged if keys matches, however, I have a doubt where should I have to join the data at the end producer or consumer in my case that the current workflow is the following
1 - scrape all databases ( multiples clients) (simulate)
2 - pushes to manager (proxy level server) where multiples clients send its data to the manger
3 - Merge multiple data sources into one list as per incoming data no DB operations yet example {"ID-2002-0201": {"id":"ID-2002-0201","updated_at":"2018-05-14T22:25:51Z","html_url":"xxxxxxxxxxxx"}} > maybe producer
4 - use a get_or_create ( check in the database if there isnt a record with that data , otherwise create it) > consumer
5 - create a bulk of data (maybe chunk the data into smaller chunks to be scalable when growing data source from 2 to 100+) > consumer
server.py
# #!/usr/bin/env python3
import asyncio
import logging
import random
from pipeline_async import Pipeline

class A:
    def __init__(self):
        pass

    def run(self):
        return {"ID-2002-0201":{"id":"ID-2002-0201","updated_at":"2018-05-14T22:25:51Z","html_url":"xxxxxxxxxxxx"}}

class B:
    def __init__(self):
        pass

    def run(self):
        return {"ID-2002-0202":{"id":"ID-2002-0202","updated_at":"2018-05-14T22:25:51Z","html_url":"xxxxxxxxxxxx"}}

class Manager:

    async def producer(self, pipeline, data_sources):
        """Pretend we're getting a number from the network."""
        for data_stream in data_sources:
            await pipeline.set_message(data_stream.run(), "Producer")
            logging.info("Producer got message: %s", data_stream)

    async def consumer(self, pipeline):
        """ Pretend we're saving a number in the database. """
        while True:
            # wait for an item from the Producer
            message = await pipeline.get_message("Consumer")
            # process the msg
            logging.info(
                "Consumer storing message: %s", message
            )
            # simulate i/o operation using sleep
            await asyncio.sleep(random.random())
            pipeline.task_done()

    async def start(self):
        pipeline = Pipeline()
        data_sources = [A(),B()]
        # schedule the consumer
        consume = asyncio.ensure_future(self.consumer(pipeline))
        # run the producer and wait for completion
        await self.producer(pipeline, data_sources)
        # wait until the consumer has processed all items
        await pipeline.join()
        # the consumer is still awaiting for an item, cancel it
        consume.cancel()
        logging.info("Successfully shutdown the service.")

if __name__ == '__main__':
    asyncio.run(Manager().start())

pipeline.py
class Pipeline(asyncio.Queue):
    def __init__(self):
        super().__init__(maxsize=10)

    async def get_message(self, name):
        logging.debug("%s:about to get from queue", name)
        value = await self.get()
        logging.debug("%s:got %s from queue", name, value)
        return value

    async def set_message(self, value, name):
        logging.debug("%s:about to add %s to queue", name, value)
        await self.put(value)
        print(name, value)
        logging.debug("%s:added %s to queue", name, value)

I would appreciate some feedback on cases I missed


texts: Method to hide/show table columns with React/JSX

texts:
I am writing a function inside of a React component to hide/show columns in a table. The table is generated from an imported config object containing objects which model the column data. We render by simply mapping over the table content and rendering cells based on the columns. The method I'm writing exists in the table component and accepts a string corresponding to the targetProp property inside of a column object. Additionally, the table needs to render a child component which serves as an actual toggle menu.

  toggleTableColumn(targetProp: string) {
    const allColumns = tableConfigMap[this.configName].columns; //an array of all column objects available for display
    const targetColumnIndex = _.findIndex(allColumns, { targetProp }); // original index of target column, used for re-inserting in correct order
    const targetColumn = allColumns[targetColumnIndex];
    const displayedColumns = [...this.tableConfig.columns];

    const columnShown = !_.isUndefined(_.find(displayedColumns, { ...targetColumn }));

    if (columnShown) {
      const adjustedColumns = _.without(this.tableConfig.columns, targetColumn);
      this.tableConfig = { ...this.tableConfig, columns: adjustedColumns };
    } else {
      const adjustedColumns = displayedColumns;
      adjustedColumns.splice(targetColumnIndex, 0, targetColumn);
      this.tableConfig = { ...this.tableConfig, columns: adjustedColumns };
    }
  }

I'm feeling like there must be a more elegant way to do this. I'm attempting not to add some kind of isVisible prop to the table column objects as it seems wrong to put this kind of view logic into the data model.

The child component menu will contain a dropdown list of all the columns with checkboxes corresponding to visible/invisible columns. It seems to me like not only would I have to pass this toggle function to the menu component, I'd also have to pass the list of all columns AND the list of selected columns as props to the menu component in order to properly render the checkbox styles (checked or unchecked).

This feels very sloppy, there must be a more elegant way. I hope this makes sense.