texts:
pathmunge is an often-seen function in shell initialization files, used to add entries to the PATH environment variable without duplication. Examples:

Fedora /etc/profile's pathmunge.
How can I cleanly add to $PATH? - Unix & Linux
Unix shell function for adding directories to PATH

I wrote this pathmunge variation in zsh:

pathmunge() {
    local path_array before
    # The default is to prepend the argument to PATH
    before=1
    case $1 in
        after)
            # Append to PATH
            before=
            ;&
        before)
            shift
            ;;
    esac
    # Split PATH on : into an array
    path_array=(${(As.:.)PATH})
    # Then remove the arguments from it, since they are to be added in the
    # order specified
    path_array=(${path_array:|argv})
    if [[ -n $before ]]
    then
        # Reverse the order of the arguments, so that:
        #    for f in ...; pathmunge f
        # and
        #    pathmunge ...
        # have the same effect.
        path_array=(${(Oa)argv} $path_array)
    else
        path_array=($path_array $argv)
    fi
    # Concatenate the array back to PATH
    PATH="${(j.:.)path_array}"
}

Note on implementation: Usually pathmunge implementations don't add to PATH if the entry already exists. I took a slightly different path - I'll remove the old instance of entry, and then add the entry as specified. The purpose is to ensure that entries are available in the expected order, since the order matters.

For example, if an entry /foo has commands shadowing another entry /bar, and I do pathmunge before /foo or pathmunge after /foo with PATH already containing /foo and /bar in some order, I can reasonably expect that now PATH will have the expected relative order between /foo and /bar.

Compatibility with other shells is not a concern. I am fairly competent when it comes to shell scripts. However, I have never made much use of zsh's extensive parameter expansion features. So, I'm looking for pitfalls and performance improvements.


texts:
I'm looking to port a Python script I have over to Swift, partly for some performance benefits, and partly to dip my toe into a new language.

My program computes what is called the downset of a permutation of \$[n] := \{1,2,\cdots,n\}\$. For me, a permutation of \$[n]\$ is a tuple containing each integer precisely once. Deleting the entry \$\pi(i)\$ from a permutation \$\pi = \pi(1) \pi(2) \cdots \pi(n)\$ produces a permutation \$\sigma = \pi(1) \pi(2) \cdots \pi(i-1) \pi(i+1) \cdots \pi(n)\$ with each entry larger than \$\pi(i)\$ lowered by \$1\$. The downset of a permutation is the set of all permutations which can be obtained by a sequence of such deletions. I'm calculating it so that the downset is sorted by rank: I'll return an array L such that L[m] is the set of permutations in the downset of length m.

Here's the working Python3 code I have:

def one_deletion(sigma,i):
    """ Deletes by value, not by index.
    """
    smaller_perm = tuple(val if val < i else val-1 for val in sigma if val != i)
    return smaller_perm

def downset(pi):
    L = []
    new_perms = {pi}
    L.append(new_perms)
    for _ in range(len(pi)):
        old_perms = new_perms
        new_perms = set()
        for sigma in old_perms:
            new_perms.update(one_deletion(sigma,i) for i in sigma)
        L.append(new_perms)
    return L[::-1]

if __name__ == "__main__":
    u3 = tuple([2,5,3,1,4])
    print(downset(u3))

In trying to port this to Swift code, I've learned a lot! Here's my code:

struct Permutation: Hashable {
    let perm : Array<Int>
    var hashValue: Int {
        return perm.description.hashValue
    }
    static func == (lhs: Permutation, rhs: Permutation) -> Bool {
        return lhs.perm == rhs.perm
    }
}

func one_deletion (sigma: Permutation, i: Int) -> Permutation {
    var A = [Int]() // Empty array of integers
    for val in sigma.perm {
        if val < i {
            A.append(val)
        } else if val > i {
            A.append(val-1)
        }
    }
    let B = Permutation(perm:A)
    return B
}

func downset (pi: Permutation) -> [Set<Permutation>] {
    var L = [Set<Permutation>]()
    var new_perms = Set([pi])
    L.append(new_perms)

    for _ in pi.perm {
        let old_perms = new_perms
        new_perms = []
        for sigma in old_perms {
            for val in sigma.perm {
                new_perms.insert(one_deletion(sigma:sigma, i:val))
            }
        }
        L.append(new_perms)
    }
    return L
}

let u3 = Permutation(perm:[2,5,3,1,4])
print(downset(pi: u3))

Now, some questions!

Is there a better way to make an array of integers hashable in Swift? Here, two Permutation objects are the same when they're literally the same tuple, so hashing by description works.
Are there any obvious things I'm doing wrong in Swift? In practice, this code is slower than my Python code.

Any general purpose comments are encouraged as well.


texts: K&R - The C programming language Exercise1-12

texts:
I am working through the K&R and just finished exercise 1-12 and below is my solution.
Exercise1-12: Write a program that prints input one word per line.

#include <stdio.h>

main()
{
    int c;

    while((c = getchar()) != EOF)
    {
        if(c == ' ' ||  c == '\t' || c == '\n')
        {
            putchar('\n');
            while(c == ' '|| c == '\t' || c == '\n')
             c = getchar();
        }
        putchar(c);
    }
}

My question is both author and solutions here defined and used the state variable.
when we compare my solution is pretty simple but it works. am I missing something? maybe there is a case that my solution won't work well?

Looking for your comments to improve, Thanks


texts: Using BigDecimal to validate epoch timestamp in exponential notation

texts:
I have some phone records in which epoch time is coming in exponential format like 1467.738871E9. I need to validate those records in which number is not in proper format and drop those records. Right now, I am using big decimal, but I have heard that bigdecimal is slow and takes more space. Since I have million of records to be validated, is there any other way to validate time which is more space- and time-efficient?

try{
    new BigDecimal(data).toBigInteger();}
    catch(NumberFormatException n){
      return false;
    }
return true;

Examples of valid timestamps:

1.467983982E9
1.468119771E9
1467858808E9
1.468119771E11
1468119771E11

Examples of invalid timestamps:

1.46A802215E9
null
4.1B46A802215E9


texts: Shorter way to write list-as-dict-value in Python?

texts:
I have a data structure that looks like this:

a = {
     'red': ['yellow', 'green', 'purple'],
     'orange': ['fuschia']
    }

This is the code I write to add new elements:

if a.has_key(color):
    a[color].append(path)
else:
    a[color] = [path]

Is there a shorter way to write this?


texts:
New to the C language. Which design mistakes have I made in my first C program? Or what can I improve? Any little detail is appreciated.

Note: I have experience in multiple coding languages. (this is the beginning of my C journey)

Description of the program: checks if a string/array of characters is a bit string. Example: "010100" -> valid.

#include <stdio.h>
#include <string.h>

int main() {
    char str[100];
    fgets(str, 100, stdin);

    int len = strlen(str);
    int len2 = len - 1;
    int count = 0;

    //loop through string
    for(int i = 0; i < len2; i++) {
        switch (str[i]) {
            case '0':
            case '1':
                count++;
                break;
        }
    }

    //is string a bit string
    if (count == len2)
        printf("Valid!\n");
    else
        printf("Not Valid...\n");

    return 0;
}


texts:
I have an array of date objects, which I want to group by year and month. The data structure I have chosen for my target is an array of arrays of Date objects.

Two Date objects should be in the same array if year AND month match up.

I'm supplying two extensions I added to Date and Formatter to easily extract year and month of a given date, as well as creating date objects more easily.

import Foundation

extension Formatter {

    static let year: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy"
        return formatter
    }()

    static let monthString: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "LLL"
        return formatter
    }()

    static let monthInt: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "LL"
        return formatter
    }()
}

extension Date {

    var monthString: String  { return Formatter.monthString.string(from: self) }
    var monthInt: Int { return Int(Formatter.monthInt.string (from:self))! }
    var yearInt: Int { return Int(Formatter.year.string(from: self))!}

    static func from(year: Int, month: Int, day: Int) -> Date {
        let gregorianCalendar = NSCalendar(calendarIdentifier: .gregorian)!

        var dateComponents = DateComponents()
        dateComponents.year = year
        dateComponents.month = month
        dateComponents.day = day

        let date:Date = gregorianCalendar.date(from: dateComponents)!
        return date
    }

    static func parse(_ string: String, format: String = "yyyy-MM-dd") -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = NSTimeZone.default
        dateFormatter.dateFormat = format

        let date = dateFormatter.date(from: string)!
        return date
    }
}

I then created a helper class with a static method to encapsulate the functionality:

class DateArrayConversionHelper {

    static func sortDateByMonth(dateArray:[Date]) -> [[Date]] {

        //create a copy of input array and sort it

        var inputArray:[Date] = dateArray
        inputArray.sort()

        //create target data structure

        var resultArray:[[Date]] = [[]]

        //set initial variable and add it to target data structure

        resultArray[0].append(inputArray[0])
        var k = 0

        for i in 1 ..< (inputArray.count) {

            if (inputArray[i].yearInt == inputArray[i-1].yearInt)
                && (inputArray[i].monthInt == inputArray[i-1].monthInt) {
                    resultArray[k].append(inputArray[i])
                }
            else {
                    k = k+1
                    resultArray.append([])
                    resultArray[k].append(inputArray[i])
                }
        }

    return resultArray
    }
}

For testing:

let randomDates:[Date] = [Date.parse("2014-05-20"), Date.parse("2012-07-21"), Date.parse("2012-07-01"), Date.parse("2017-01-24"), Date.parse("2017-01-11"), Date.parse("2017-01-14"), Date.parse("2000-01-02"), Date.parse("2000-05-20")]

let resultData:[[Date]] = DateArrayConversionHelper.sortDateByMonth(dateArray: randomDates)

I'm looking for ways to improve my algorithm. I'm also still pretty new to Swift so if you're wondering why I didn't do/use x, it's usually because I didn't know better.

My end game is to use these arrays as a source for a UITableView.


texts: Manipulating an ES6 static class property that is an array

texts:
I've been trying to find a way to create static properties in ES6 classes and have found a solution with the help of various Stack Overflow answers (namely this one and this one).

However, I also wanted to take this a step further and make the static property an array that can be updated/added to using a special static method. I've managed to come up with something that works. Here is a complete demonstration using the class Apple and static property possibleColors:

    class Apple
    {
      constructor(args = {})
      {
        this.color = args.color || 'red';
        this.description = args.description || 'An apple.';
      }

      static get possibleColors()
      {
        if (!this._possibleColors)
          this._possibleColors = ['red', 'green', 'yellow'];
        return this._possibleColors;
      }

      static set possibleColors(arr)
      {
        if (Array.isArray(arr))
          this._possibleColors = arr;
        else
          console.log("Possible colors must be an array.")
      }

      static addPossibleColor(c)
      {
        if (!this._possibleColors)
          this._possibleColors = this.possibleColors;
        this._possibleColors.push(c);
      }

      get color()
      {
        if (!this._color)
          this._color = '';
        return this._color;
      }

      set color(c)
      {
        if (Apple.possibleColors.includes(c))
          this._color = c;
        else
        {
          console.log(`Color '${c}' is not a valid apple color.`);
          if (!this._color)
            this._color = 'red';
        }
      }
    }

The possibleColors property belongs to the class only and will not be a part of new instances. I've also taken measures to ensure that its value is always an array. It defaults to red, green, & yellow, but you can view/change possible colors using the regular getter/setter:

Apple.possibleColors = ['color', 'othercolor']

You can also add new possible colors like this:

Apple.addPossibleColor('newcolor')

In this example, the whole point of having the possibleColors static property is to have a definitive list of valid colors stored in the main class and prevent any Apple instances from being set to a color not in the array. Of course, I can think of other use cases for this kind of technique.

For example, I'm currently trying to write my own basic component system that uses templates to draw/render each component as HTML on the page. The main class (Component or similar) would have a static property for storing the templates in an array, and you'd choose a template from this array when instantiating a component (or it would choose a default if none specified).

What I'd like to know:

Could this approach cause any problems I haven't foreseen (either in this specific scenario or a more complex one)?
Are there better ways to do anything I've demonstrated here?
Is the way I'm handling static properties overall considered good practice?


texts:
I had to do a small application using a menu system and Turtle. I have finished it and worked perfect. Just to make sure, can you please check it if it has done properly?

#!/usr/bin/python

## draw_shape.py

import turtle as t

def how_many():
    while True:
        print "  How many of then do you want to draw?"
        print "  -Range is from 1 to 5-"
        global shape_no
        shape_no = raw_input('  Enter your choice: ')
        try:
            shape_no = int(shape_no)
            if (1 <= shape_no <= 5):
                print "Your number is ok"
                break
            else:
                print
                print "from 1 to 5 only"
        except:
            print "Only numbers allowed - Please try again"
    return True

#=========#=========#=========#=========#=========#=========#=========#
def start_point():
    t.penup()
    t.setpos(-240,0)
    t.pendown()

def draw_square(howmanyof):
    start_point()
    for a in range(howmanyof):
        for a in range(4):
            t.forward(80)
            t.left(90)
        t.penup()
        t.forward(100)
        t.pendown()

def draw_triangle(howmanyof):
    start_point()
    for a in range(howmanyof):
        for a in range(3):
            t.forward(80)
            t.left(120)
        t.penup()
        t.forward(100)
        t.pendown()

def draw_rectangle(howmanyof):
    start_point()
    for a in range(howmanyof):

        for a in range(2):
            t.forward(80)
            t.left(90)
            t.forward(40)
            t.left(90)
        t.penup()
        t.forward(100)
        t.pendown()

def draw_hexagon(howmanyof):
    start_point()
    for a in range(howmanyof):
        for a in range(6):
            t.forward(50)
            t.left(60)
        t.penup()
        t.forward(110)
        t.pendown()

def draw_octagon(howmanyof):
    start_point()
    for a in range(howmanyof):
        for a in range(8):
            t.forward(40)
            t.left(45)
        t.penup()
        t.forward(110)
        t.pendown()

def draw_circle(howmanyof):
    start_point()
    for a in range(howmanyof):
        t . circle(50)
        t.penup()
        t.forward(120)
        t.pendown()

#=========#=========#=========#=========#=========#=========#=========#
def main():
    while True:
        print
        print "  Draw a Shape"
        print "  ============"
        print
        print "  1 - Draw a square"
        print "  2 - Draw a triangle"
        print "  3 - Draw a rectangle"
        print "  4 - Draw a hexagon"
        print "  5 - Draw an octagon"
        print "  6 - Draw a circle"
        print
        print "  X - Exit"
        print

        choice = raw_input('  Enter your choice: ')

        if (choice == 'x') or (choice == 'X'):
            break
        elif choice == '1':
            how_many()
            draw_square(shape_no)
        elif choice == '2':
            how_many()
            draw_triangle(shape_no)
        elif choice == '3':
            how_many()
            draw_rectangle(shape_no)
        elif choice == '4':
            how_many()
            draw_hexagon(shape_no)
        elif choice == '5':
            how_many()
            draw_octagon(shape_no)
        elif choice == '6':
            how_many()
            draw_circle(shape_no)
        else:
            print
            print '  Try again'
            print

#=========#=========#=========#=========#=========#=========#=========#
if __name__ == "__main__":
    main()

#=========#=========#=========#=========#=========#=========#=========#


texts:
I have an account page where I have three forms. A user can change his name, his email address, and his password.

There are two difficulties I am having from trying to do this:

1) the request.user information is not updating accordingly (e.g., it will lag behind by one change or it will update if the form is not validated)

2) I have three separate forms, however, when I submit one form, I will get validation messages from another form. For example, if I submit the "Change Name" form, I will get 'This field is required from the password fields in the password form. Here is what I currently have --

in forms:

# in forms.py
from django.contrib.auth.models import User

class ChangeNameForm(ModelForm):
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)
    class Meta:
        model = User
        fields = ('first_name', 'last_name' )

class ChangeEmailForm(ModelForm):
    email = forms.EmailField(required=True)
    class Meta:
        model = User
        fields = ('email',)

in views:

@login_required
def account(request):
    name_message = password_message = email_message = ''
    change_name_form = ChangeNameForm(data=request.POST or None, instance=request.user)
    change_password_form = PasswordChangeForm(data=request.POST or None, user = request.user)
    change_email_form = ChangeEmailForm(data=request.POST or None, instance=request.user)
    if request.method == "POST":
        if "change_name" in request.POST and change_name_form.is_valid():
            change_name_form.save()
            name_message = 'Your name has been changed.'
        if "change_password" in request.POST and change_password_form.is_valid():
            change_password_form.save()
            password_message = 'Your password has been changed.'
        if "change_email" in request.POST and change_email_form.is_valid():
            ...
            email_message = 'Please click the link in your email to confirm changes.'
    return render_to_response('userprofile/account.html',
                       {'change_name_form': change_name_form,
                        'change_email_form': change_email_form,
                        'change_password_form': change_password_form,
                        'password_message': password_message,
                        'name_message': name_message,
                        'email_message': email_message,},
                        context_instance=RequestContext(request))

in template:

Change Name

    <form method="post" action="/account/change/" name='name'> {% csrf_token %}

Change name: {{user.first_name}} {{user.last_name}}

{{change_name_form.as_table}}

{{name_message}}

<input type="submit" value="Save Changes" name="change_name"/>

    </form>

Change Email

    <form method="post" action="/account/change/" name='email'> {% csrf_token %}

Change email: {{user.email}}

{{change_email_form.as_table}}

{{email_message}}

<input type="submit" value="Save Changes" name="change_email" />

    </form>

Change Password

    <form method="post" action="/account/change/" name='password'> {% csrf_token %}

Change password

{{change_password_form.as_table}}

{{password_message}}

<input type="submit" value="Save Changes" name="change_password"/>

    </form>

What do I need to do to solve the two issues of making sure the request.user information is current and making sure validation only runs for the current form? Also, would it be possible to run a for loop to reduce redundancy in the template code? If so, how would I do this given the fact that the two name fields?. Thank you.


texts:
I had to jump on the bandwagon for this one. The task does a great job of helping you learn a language you're unfamiliar with.

So today I present you with my version of the infamous FizzBuzz game in Common Lisp. This is really the first "program" I've made in CLISP, and even though it's pretty small, I'm quite proud!!

I'd really love to know if there's an even easier way to make the same functionality. I notice a lot of repetition in terms of is-multiple, so if anyone has any ideas how I could DRY up all that, I'd appreciate it. Also, is there a formatting standard for symbol names and such in Lisp?

fizzbuzz.lisp

(defun is-multiple (i against)
  (= (mod i against) 0))
(defun num-action (i)
  (cond ((and (is-multiple i 3) (is-multiple i 5)) (print "FizzBuzz"))
    ((is-multiple i 3) (print "Fizz"))
    ((is-multiple i 5) (print "Buzz"))
    (T (print i))))
(dotimes (i 101) (num-action i))

Can it be cleaned up any further?


texts:
The puzzle goes like this: in a rectangular 2D grid there are empty spaces (.), exactly one starting point (S, s) and obstacles (denoted below by X's). The objective of the puzzle is to find a path starting at the starting point and going through each empty space exactly once (a Hamiltonian path). You can't, of course cross the obstacles. You can move horizontally and vertically. A typical puzzle would look like this:

......
.SX...
...X..
.....X
......
XX....
......

And its solution:

11 12 13 14 17 18
10 1  X  15 16 19
9  2  3  X  21 20
8  5  4  23 22 X
7  6  25 24 29 30
X  X  26 27 28 31
37 36 35 34 33 32

I wrote a solver in Python 3 (I later learned that this algorithm is actually a simple DFS). It solves the puzzle above in ~0.9 s, which is very good, but I was wondering if I can perhaps optimize it somehow.

import time

EMPTY_SPACE_SYMBOLS = ['.']
STARTING_POINT_SYMBOLS = ['S', 's']
OBSTACLE_SYMBOL = 'X'
PUZZLE_PATH = "grid.txt"
DIRS = [(-1, 0), (1, 0), (0, 1), (0, -1)]

start_time = time.time()

grid = open(PUZZLE_PATH).read().splitlines()
H = len(grid)
W = len(grid[0])
assert all(len(row) == W for row in grid), "Grid not rectangular"

def print_solution(coords):
    result_grid = [[OBSTACLE_SYMBOL for _ in range(W)] for _ in range(H)]
    for i, (r, c) in enumerate(coords, start=1):
        result_grid[r][c] = i
    str_grid = [[str(item).ljust(3) for item in row] for row in result_grid]
    print('\n'.join(' '.join(row) for row in str_grid))

def extend(path, legal_coords):
    res = []
    lx, ly = path[-1]
    for dx, dy in DIRS:
        new_coord = (lx + dx, ly + dy)
        if new_coord in legal_coords and new_coord not in path:
            res.append(path + [new_coord])
    return res

start_pos = None
legal = set()
for r, row in enumerate(grid):
    for c, item in enumerate(row):
        if item in STARTING_POINT_SYMBOLS:
            assert start_pos is None, "Multiple starting points"
            start_pos = (r, c)
        elif item in EMPTY_SPACE_SYMBOLS:
            legal.add((r, c))

assert start_pos is not None, "No starting point"

TARGET_PATH_LEN = len(legal) + 1
paths = [[start_pos]]
found = False
number_of_solutions = 0

while paths:
    cur_path = paths.pop()
    if len(cur_path) == TARGET_PATH_LEN:
        number_of_solutions += 1
        if not found:
            print_solution(cur_path)
            print("Solution found in {} s".format(time.time() - start_time))
        found = True
    paths += extend(cur_path, legal)

print('Total number of solutions found: {} (took: {} s)'.format(number_of_solutions, time.time() - start_time))


texts: Production code to be good for unit testing

texts:
I would like to advise if the following production code is good to be unit tested. The segment of  the production code gets data from a backend service and displays it on the page. It is a class:

...
// Extract this code into a separate method because it is called in more than 1 place
Keywords.prototype.addKeyword = function(keyword) {
    $("ul").append("<li>" + keyword + "</li>");
}

// This is the method that I want to test
Keywords.prototype.getKeywords = function(forGroup) {
    // AppDao contains a bunch of methods that get data
    var keywords = AppDao.getKeywords(forGroup),
        that = this;

    $.each(keywords, function(i, keyword) {
        that.addKeyword(keyword);
    };
}
...

I'm planning to test it in the following way:

Stub Keywords.prototype.addKeyword() and make sure that it will be called with 3 arguments: "KW A", "KW B", and "KW C"
Stub AppDao.getKeywords() and make sure that it will be called with "Test Group" and will return 3 keywords: "KW A", "KW B", and "KW C"
Invoke Keywords.prototype.getKeywords() and verify the stubs

I didn't start the actual implementation of the test yet because I would like to advise with you guys if you think that something can be better done. Thanks.


texts: ConsoleWorker update console timer with how long application has been open

texts:
earlier I coded a quick console worker that runs a timer every 1 second and updates the consoles timer with how long the app has been open, how can I improve this?

using Faze.Other.App;
using log4net;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Faze.Other.Util.Console
{
    class ConsoleWorker : IDisposable
    {
        /// <summary>
        /// Holds an instance of Timer.
        /// </summary>
        private Timer consoleWorkerTimer;

        /// <summary>
        /// Interval of the ConsoleWorker timer.
        /// </summary>
        private int consoleWorkerInterval = 1000;

        /// <summary>
        /// Holds an instance of ILog.
        /// </summary>
        private ILog classLogger;
        /// <summary>
        /// Initializes a new instance of ConsoleWorker.
        /// </summary>
        public ConsoleWorker()
        {
            if (StaticSettings.includeSecondsInUptimeString && consoleWorkerInterval < 1000)
                consoleWorkerInterval = 1000;

            classLogger = LogManager.GetLogger(typeof(ConsoleWorker));
            consoleWorkerTimer = new Timer(new TimerCallback(timerElapsed), null, TimeSpan.FromMilliseconds(consoleWorkerInterval), TimeSpan.FromMilliseconds(consoleWorkerInterval));
        }

        /// <summary>
        /// Starts the worker (timer) process.
        /// </summary>
        public void startWorker()
        {
            // I'll leave this for now..
        }

        /// <summary>
        /// Handles the timers callback once elapsed.
        /// </summary>
        /// <param name="timerObject">ConsoleWorker timer's object.</param>
        private void timerElapsed(object timerObject)
        {
            if (Faze.getServer().getServerInformation().hasStarted())
            {
                if (StaticSettings.advancedLoggingWhenDebugging && Debugger.IsAttached)
                    classLogger.Info("ConsoleWorker has elapsed -> " + DateTime.Now.ToLongTimeString());

                TimeSpan serverUptime = DateTime.Now - Faze.getServer().getServerInformation().getStartedTime();

                string consoleTitleString = string.Empty;

                if (StaticSettings.includeSecondsInUptimeString)
                {
                    consoleTitleString = Faze.getServer().getServerInformation().getProjectName() + " / " + serverUptime.Days + " day" + (serverUptime.Days != 1 ? "s" : "")
                    + ", " + serverUptime.Hours + " hour" + (serverUptime.Hours != 1 ? "s" : "") + ", " +
                    serverUptime.Minutes + " minute" + (serverUptime.Minutes != 1 ? "s" : "") + " and " + serverUptime.Seconds + " second" + (serverUptime.Seconds != 1 ? "s" : "");
                }
                else
                {
                    consoleTitleString = Faze.getServer().getServerInformation().getProjectName() + " / " + serverUptime.Days + " day" + (serverUptime.Days != 1 ? "s" : "")
                    + ", " + serverUptime.Hours + " hour" + (serverUptime.Hours != 1 ? "s" : "") + " and " +
                    serverUptime.Minutes + " minute" + (serverUptime.Minutes != 1 ? "s" : "");
                }

                System.Console.Title = consoleTitleString;
            }
        }

        public void Dispose()
        {
            consoleWorkerTimer.Dispose();
        }
    }
}


texts: Insert value into multiple locations in a list

texts:
Code
insertAt :: a -> [Int] -> [a] -> [a]
insertAt x indices xs = go 0 xs
  where
    go _ [] = []
    go j (y:ys)
      | nextIndex `elem` indices = y : x : go (nextIndex + 1) ys
      | otherwise = y : go nextIndex ys
      where
        nextIndex = j + 1

Questions

How can I make this code more efficient?
How can I make the code easier to follow?
Is a recursive approach the correct one?
Do the Prelude or Data.List have any functions that could make this more readable/efficient?


texts: A bash script to submit an AWS EMR job and poll until the cluster terminates

texts:
#!/bin/bash
set -ue

# use AWS CLI to launch a cluster
create_cluster_response=$(aws emr create-cluster \
  --release-label emr-4.3.0 \
  --region us-east-1 \
  --etc) # many more arguments; see http://docs.aws.amazon.com/cli/latest/reference/emr/create-cluster.html

# use jq to parse and display result
cluster_id=$(echo "${create_cluster_response}" | jq -r '.ClusterId')
echo "ClusterId=${cluster_id}"
echo "AWS Management Console URL: https://console.aws.amazon.com/elasticmapreduce/home?region=us-east-1#cluster-details:${cluster_id}"

# block until the EMR cluster terminates
previous_state=''
while true; do
  json=$(aws emr describe-cluster --cluster-id ${cluster_id}) # see http://docs.aws.amazon.com/cli/latest/reference/emr/describe-cluster.html
  state=$(echo "${json}" | jq -r '.Cluster.Status.State')
  # echo state changes
  if [[ ${state} != ${previous_state} ]]; then
    now=$(date -u +"%Y-%m-%dT%H:%M:%SZ") # format date as ISO 8601 UTC
    message=$(echo "${json}" | jq -r '.Cluster.Status.StateChangeReason.Message')
    echo "${now} ${state} ${message}"
    previous_state="${state}"
  fi
  # terminate this script when the cluster terminates
  if [[ ${state} == TERMINATED ]]; then
    echo "EMR JOB SUCCESS"
    exit 0
  fi
  if [[ ${state} == TERMINATED_WITH_ERRORS ]]; then
    echo "EMR JOB FAILURE"
    exit 1
  fi
  sleep 10
done

I am very new to programming bash and will appreciate any and all feedback.


texts:
I am working with Youtube OAuth for the first time and I am not that great when it comes to security. I got the following code and would like to hear if you guys can find any security issue:

    $code = $_GET['code'];

    $url = 'https://accounts.google.com/o/oauth2/token';

    $params = array(
        "code" => $code,
        "client_id" => "XXX",
        "client_secret" => "YYY",
        "redirect_uri" => "URL",
        "grant_type" => "authorization_code"
    );

    $curl = curl_init($url);

    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $json_response = curl_exec($curl);
    curl_close($curl);
    $authObj = json_decode($json_response);

    $accountInfo = get_data('https://www.googleapis.com/youtube/v3/channels?part=id&mine=true&access_token='.$authObj->access_token.'');

    $accountInfo = json_decode($accountInfo, true);

    $linkedAccount = $db->QueryFetchArrayAll("SELECT * FROM `youtube_accounts` WHERE `channel_id`='".$accountInfo['items'][0]['id']."'");
    $accountExists = $db->QueryFetchArrayAll("SELECT * FROM `youtube_accounts` WHERE `user_id`='".$data['id']."' AND `status` != 3");


texts:
I'm currently working in a Windows.Forms project where its very common that I need to show a responsive feedback form while a task runs. These tasks take typically around 5 to 10 seconds to complete and the user can't do anything else until the task has successfully finished or failed.

To keep the UI responsive I've cooked up a little helper class. I'm pretty new to tasks and the async programming environment so I am not sure if I'm overkilling things here or going off in a completely wrong direction:

This is the small helper class:

internal sealed class TaskManagerWithFeedbackDialog<TController> where TController : IViewController, new()
{
    public static Task<TReturn> RunTask<TReturn>(Func<TReturn> func)
    {
        if (func == null)
        {
            throw new ArgumentNullException("func");
        }

        var manager = new _AsyncTaskManager<TReturn>(func);

        using (var view = new TController())
        {
            var task = manager.Start(view);
            view.ShowViewDialog();
            return task;
        }
    }

    private class _AsyncTaskManager<T>
    {
        private readonly Func<T> taskFunc;

        public _AsyncTaskManager(Func<T> func)
        {
            taskFunc = func;
        }

        public Task<T> Start(IViewController feedBackView)
        {
            var task = Task.Factory.StartNew(taskFunc);

            task.ContinueWith(t =>
            {
                feedBackView.CloseView();
            }, TaskContinuationOptions.OnlyOnFaulted);

            task.ContinueWith(t =>
            {
                feedBackView.CloseView();
                return t.Result;
            }, TaskContinuationOptions.NotOnFaulted);

            return task;
        }
    }
}

Where the implementation of IViewController.CloseView() would look like this:

public virtual void CloseView()
{
    if (View.InvokeRequired)
    {
        View.Invoke(new Action(View.Close));
    }
    else
    {
        View.Close();
    }
}

Another issue I am not sure about is where is the best place to handle ArregateException?. Right now I don't handle anything as I don't need to clean up anything if a task fails. I simply check the returned task for any errors. Is this the right thing to do? Do async tasks always fail 'silently'? If I needed to clean up, where would it be? Inside .ContinueWith( .... , TaskContinuationOptions.OnlyOnFaulted)?


texts:
I have an Android project that queries the BART train API. I was curious if updating the UI inside the Retrofit onResponse method is correct or if there is a better way. Below is my code. Also, here is the GitHub link if you want to look at a different file. If there are any other issues you see please let me know. I welcome any and all feedback.

ublic class StationListFragment extends Fragment {

private StationList testList;
private RecyclerView recyclerView;
private StationListAdapter adapter;

public StationListFragment() {
// Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
  Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View v = inflater.inflate(R.layout.fragment_station_list, container, false);

// Set up RecyclerView
recyclerView = v.findViewById(R.id.station_list_recycler);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL));

// Make API call with retrofit
ApiInterface service = RetrofitClient.getClient().create(ApiInterface.class);
Call<StationList> call = service.getStations();
call.enqueue(new Callback<StationList>() {
  @Override
  public void onResponse(Call<StationList> call, Response<StationList> response) {
    // populate recycler view with the list of stations.
    if (response.isSuccessful()) {
      testList = response.body();
      adapter = new StationListAdapter(getContext(), testList.getRoot().getStations().getStation());
      recyclerView.setAdapter(adapter);
      Log.d("TAG: RESPONSE", new GsonBuilder().setPrettyPrinting().create().toJson(response));
    } else {
      int statusCode = response.code();
      Log.d("TAG: STATUSCODE", Integer.toString(statusCode));
    }
  }

  @Override
  public void onFailure(Call<StationList> call, Throwable t) {
    Log.d("TAG: FAILURE", t.getMessage());
  }
});

return v;
}
}


texts: Switching directions in iterating 2D arrays

texts:
I had to do this in a course a while back: make {1,2,3,4,5,6,7,8,9} into {{1,2,3},{6,5,4},{7,8,9}}. When doing it, I just made the inner for-loop do all the work.  But most of my friends had a Boolean and an if-statement to chose between a forward or reverse loop.

Which is more optimal and which is more readable?

private double[][] a;
public TwoD(int numRows, int numCols, double[] oneD){
    a = new double[numCols][numRows];
    int d =1;
    int x = 0;
    int i = 0;
    for (int y=0; y<numCols; y++){
        for (;x<numRows&&x>=0;x+=d){
            a[y][x] = oneD[i];
            i++;
        }
        d*=-1;
        x+=d;
    }
}

Edit: I had to have an object with a constructor which took width and height and a one dimensional array. The 1d array would be put into a 2d array as if it was a physical string being laid out (→▬▬↓←▬▬↓→▬▬).3x3 is an easy example.
1 3 9 5 4 7 3 1 5 to
1 3 9→
7 4 5←
3 1 5→

The alternative would be like (is pseudo code ok when its not the code being reviewed?)

boolean right = true;
for y
    if right
        for x++
    else
        for x--
    right= !right;


texts: List sub-folders and its ID in the given path in Google Drive with Google App Script

texts:
I am trying to create a doc file which contains the list of folders in a given folder path. The Main function is the entry point.
// This function performs the operation of creating the file of the list of folders in the specific folder.
// Usage: Set the ListDocName, the ListDocFullPath, and the SpecificFolder, then just run Main function.
function Main() {
  // Set Doc (output) file name
  var ListDocName = "RootFolderList";

  // Set Doc (output) file path
  var ListDocFullPath = "/";

  // Set specific folder, and this program would list its subfolders to Doc file.
  var SpecificFolder = "/";

  CreateGoogleDocInSpecificFolder(ListDocName, ListDocFullPath);
  var DocFiles = GoogleDocsInSpecificFolder(ListDocName, ListDocFullPath);

  while(DocFiles.hasNext())
  {
    var docFile = DocFiles.next();
    var docID = docFile.getId();
    var doc = DocumentApp.openById(docID);

    var Folders = FoldersInSpecificFolder(SpecificFolder);
    while(Folders.hasNext())
    {
      var Folder = Folders.next();
      // Access the body of the document, then add a paragraph.
      doc.getBody().appendParagraph(SpecificFolder + '/' + Folder.getName() + '\t' + Folder.getId());
    }
    doc.saveAndClose();
  }
}

// FoldersInSpecificFolder function would return a FileIterator
function FoldersInSpecificFolder(FolderFullPath)
{
  if(FolderFullPath == '/')
  {
    // Return the FolderIterator in Root.
    return getFolder(FolderFullPath);
  }
  else
  {
    // getFolder return the FolderIterator
    var TargetFolders = getFolder(FolderFullPath);
    while (TargetFolders.hasNext())
    {
      var folder = TargetFolders.next();
      return folder.getFolders();
    }
  }
}

// GoogleDocsInSpecificFolder function would return a FileIterator
function GoogleDocsInSpecificFolder(docName, FolderFullPath)
{
  if(FolderFullPath == '/')
  {
    // Read files in Root, getFilesByName return the FileIterator
    var RootDocs = DriveApp.getRootFolder().getFilesByName(docName);
    return RootDocs;
  }
  else
  {
    // getFolder return the FolderIterator
    var TargetFolders = getFolder(FolderFullPath);
    while (TargetFolders.hasNext())
    {
      var folder = TargetFolders.next();
      var docFiles = folder.getFilesByName(docName);
      return docFiles;
    }
  }
}

function CreateGoogleDocInSpecificFolder(docName, FolderFullPath)
{
  var docID;
  if(FolderFullPath == '/')
  {
    // Create a new Google Doc in Root
    var docRoot = DocumentApp.create(docName);
    var docRootID = docRoot.getId();
    docRoot.saveAndClose();
    return docRootID;
  }
  else
  {
    // Create a new Google Doc in Root
    var docRoot = DocumentApp.create(docName);
    var docRootID = docRoot.getId();
    docRoot.saveAndClose();

    // Get new Google Doc file ID (Use in copy)
    var docRootFile = DriveApp.getFileById(docRootID);

    var TargetFolders = getFolder(FolderFullPath);
    while (TargetFolders.hasNext())
    {
      var folder = TargetFolders.next();

      // Copy Google Doc to correct file path
      var docFile = docRootFile.makeCopy(docName, folder);

      docID = docFile.getId();
    }

    // Delete Google Doc in Root
    DriveApp.removeFile(docRootFile);

    return docID;
  }
}

// getFolder function would return the FolderIterator which is locate at Path.
function getFolder(Path)
{
  var SubFolder;
  var arr = Path.split("/");
  for (var i = 1; i < arr.length; i = i + 1)
  {
    var FolderName = arr[i];
    if(i == 1)
    {
      SubFolder = DriveApp.getRootFolder().searchFolders("title contains '"+FolderName+"'");
    }
    else
    {
      if (SubFolder.hasNext())
      {
        var folderTemp = SubFolder.next();
        SubFolder = folderTemp.searchFolders("title contains '"+FolderName+"'");
      }
    }
  }
  return SubFolder;
}

If there is any possible improvement about potential drawback, please let me know.


texts: Stateless tooltip component using React hooks and ref

texts:
What I'm trying to create is a generic tooltip component that I can use anywhere. I decided on a stateless component and the use of hooks and ref.

Explanation

Hook, because I wanted to have a flag for hover and ref to get element width and/or height to center it correctly.

Problem ❓

Is this solution correct and will perform fast enough with the bigger amount of tooltip components on the same page (over 100)?
The solutions I've come across so far have not been satisfactory. I wonder if this idea makes a sense if so, I will develop it and publish it as an open source project (I would like to finally make a contribution! )

Demo: https://danzawadzki.github.io/react-tooltip/

Repository: https://github.com/danzawadzki/react-tooltip

Tooltip.tsx

import * as React from 'react';
import './Tooltip.scss';
import {CSSTransition} from 'react-transition-group';
import {useState} from 'react';
import {useRef} from 'react';

export interface ITooltip {
    /** Tooltip position. */
    position?: 'top' | 'left' | 'right' | 'bottom';
    /** Tooltip message content. */
    message: String;
    /** Array with details about columns to render. */
    children: JSX.Element | Array<JSX.Element> | string;
}

export interface ITooltipStyle {
    /** Distance to the left edge. */
    left?: string;
    /** Distance to the top edge. */
    top?: string;
    /** Distance to the bottom edge. */
    bottom?: string;
    /** Distance to the right edge. */
    right?: string;
}

/**
 * Tooltip component.
 *
 * @author Daniel Zawadzki <hello@danielzawadzki.com>
 * @version 1.0.0
 */
const Tooltip: React.FunctionComponent<ITooltip> = ({position = 'top', message, children}) => {
    /**
     * Hook toggling tooltip isVisible flag.
     */
    const [isVisible, setIsVisible] = useState<boolean>(false);
    const toggle = () => setIsVisible(!isVisible);

    /**
     * Reference to the component to track width and height
     */
    const node = useRef<any>(null);

    /**
     * Positioning the component using the reference
     */
    let style: ITooltipStyle = {};
    if (node.current && node.current.offsetWidth) {
        if (position === 'top' || position === 'bottom') {
            style.left = `${String(node.current.offsetWidth / 2)}px`;
        } else {
            style.top = `-${String(node.current.offsetHeight / 1.5)}px`;
        }
    }

    return (
        <div className="Tooltip">
            <div
                className="Tooltip__toggler"
                onMouseOverCapture={toggle}
                onMouseOut={toggle}
                ref={node}>
                {children}
            </div>
            <CSSTransition
                in={isVisible}
                timeout={200}
                classNames="Tooltip"
                unmountOnExit>
                <div
                    className={`Tooltip__message Tooltip__message--${position}`}
                    style={style}>
                    {message}
                </div>
            </CSSTransition>
        </div>
    );
};

export default Tooltip;

I know that there are probably a lot of bugs and areas for development there, but is it any good idea?


texts: Five functions to get the digits of a number

texts:
I'm writing a simple function: given a number, it will return a sequence or a collection of the digits in the number (in the correct order). i.e (get-digits-fn 1234567) => (1 2 3 4 5 6 7) / [1 2 3 4 5 6 7]

Below are five attempts at the same function:

(defn get-digits-1 [num]
  (->> [num '()]
       (iterate (fn [[num digits]]
                  (when (> num 0)
                    [(quot num 10) (conj digits (rem num 10))])))
       (take-while some?)
       (last)
       (second)))

(defn get-digits-2 [num]
  (when (> num 0)
    (lazy-seq (concat (get-digits-2 (quot num 10)) '((rem num 10))))))

;; Suggested by Carcigenate
(defn get-digits-3 [num]
  (->> (str)
       (map str)
       (map int)
       (into '())))

(defn get-digits-4 [num]
  (loop [n num
         res '()]
    (if (= n 0)
      res
      (recur (quot n 10) (conj res (rem n 10))))))

(defn get-digits-5 [num]
  (->>
   (iterate (fn [[n digits]]
              [(quot n 10) (conj digits (rem n 10))])
            [num '()])
   (drop-while #(not= 0 (first %)))
   (first)
   (second)))

A helper function for testing performance:

(defn quick-bench-get-digits [fn range]
  (quick-bench (->> range
                    (map fn)
                    (map (partial apply vector))
                    (into []))))

The perf results (output truncated to only show execution time mean):

eul> (quick-bench-get-digits get-digits-1 (range 1 100000))
Execution time mean : 129.516521 ms

eul> (quick-bench-get-digits get-digits-2 (range 1 100000))
Execution time mean : 128.637055 ms

eul> (quick-bench-get-digits get-digits-3 (range 1 100000))
Execution time mean : 24.267716 ms

eul> (quick-bench-get-digits get-digits-4 (range 1 100000))
Execution time mean : 25.083393 ms

eul> (quick-bench-get-digits get-digits-5 (range 1 100000))
Execution time mean : 145.430443 ms

It looks like get-digits-3 is the fastest while get-digits-4 is closely behind. (As the numbers increase, get-digits-3 outperforms get-digits-4. i.e try (range 1000000 2000000))

Any way to increase performance more without leaving Clojure land?
If mutability and Java inter-op is allowed, is there a way to increase performance?

p.s. functions 1 and 5 are almost identical. This was incremental exploration.


texts: Swap Nodes in Pairs in singly linked list

texts:
Description:

Given a linked list, swap every two adjacent nodes and return its head.

  For example, Given 1->2->3->4, you should return the list as
  2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

Code:

class Solution {
    public ListNode swapPairs(ListNode head) {

        if (head == null || head.next == null) {
            return head;
        }

        ListNode current = head;
        ListNode prev = null;
        ListNode newHead = head.next;

        while (current != null && current.next != null) {

            ListNode first  = current;
            ListNode second = current.next;

            first.next = second.next;
            second.next = first;

            // check if its not the first pair
            if (prev != null) {
                prev.next = second;
            }

            // update pointers
            current = second;
            prev = current.next;
            current = current.next.next;
        }
        return newHead;
    }
}

Questions:

The above code passes all tests, the main struggle was the swapping logic and only after I chose meaningful names first and second I was able to clear my thoughts and move forward. Again I see that the linked list involves a lot of edge cases specially managing pointers.

I would like to know if there are some good to know points to avoid common mistakes in linked lists.

PS: Other feedbacks are welcomed too


texts: Is this UnitTest for updating an object in data-access layer sensible?

texts:
I'm still trying to learn how to write good tests (and write testable code).

This is the function I want to verify,

 void IAutoTisDal.UpdateRange(Range range)
  {
     using (var repo = _repositoryFactory.GetRepository(_baseline))
     {
        var rangeqry = from r in repo.Query<Range>()
                       where r.Id == range.Id
                       select r;
        var rangeToUpdate = rangeqry.SingleOrDefault();
        if (rangeToUpdate == null)
           throw new Exception(string.Format("Range ID {0} not found", range.Id));

        rangeToUpdate.Status = range.Status;
        rangeToUpdate.FirstPsn = range.FirstPsn;
        rangeToUpdate.LastPsn = range.LastPsn;
        rangeToUpdate.PageCount = (int)(range.LastPsn - range.FirstPsn);
        rangeToUpdate.CourierId = range.CourierId;
        rangeToUpdate.WorkflowServer = range.WorkflowServer;
        rangeToUpdate.DoubleFeedInd = range.DoubleFeedInd;

        repo.Commit();
     }
  }

And the unit test:

  [TestMethod]
  public void UpdateRange_RangesPropertiesAreCopied()
  {
     var rangeToUpdate = new Range()
     {
        Id = 1, CourierId = 0, Status = 20,
        WorkflowServer = null,
        FirstPsn = -1, LastPsn = -1, PageCount = 0
     };
     var rangeToSave = new Range()
     {
        Id = 1, CourierId = 1234, Status = 40,
        WorkflowServer = new PhysicalStation(){ Id = 1, Name = "fakeserver"},
        FirstPsn = 123, LastPsn = 456, PageCount = 333
     };
     var repoMock = new Mock<IRepository>();
     repoMock.Setup(x => x.Query<Range>()).Returns(new List<Range>(new[] {rangeToUpdate}).AsQueryable()).Verifiable();
     repoMock.Setup(x => x.Commit()).Verifiable();
     var factoryMock = new Mock<IRepositoryFactory>();
     factoryMock.Setup(x => x.GetRepository(It.IsAny<string>())).Returns(repoMock.Object);
     IAutoTisDal dal = new AutoTisDal(factoryMock.Object, "");

     dal.UpdateRange(rangeToSave);

     repoMock.VerifyAll();

     Assert.AreEqual(rangeToUpdate.Id, rangeToSave.Id);
     Assert.AreEqual(rangeToUpdate.CourierId, rangeToSave.CourierId);
     Assert.AreEqual(rangeToUpdate.LastPsn, rangeToSave.LastPsn);
     Assert.AreEqual(rangeToUpdate.FirstPsn, rangeToSave.FirstPsn);
     Assert.AreEqual(rangeToUpdate.PageCount, rangeToSave.LastPsn - rangeToSave.FirstPsn);
     Assert.AreSame(rangeToUpdate.WorkflowServer, rangeToSave.WorkflowServer);
     Assert.AreEqual(rangeToUpdate.Status, rangeToSave.Status);
  }

I know I need to write another test against the expected exception if no RangeId matches.

I also realize I'm writing test after the code.


texts: Reviewing my implementation of a stack using linked list

texts:
I have been studying data structures, and I'm new to this.  Here is my code for the push and pop operations.

I considered using a node=top, so that I can avoid O(n) operations for the push (i.e. finding the last node every time).
I can't seem to find a better implementation for the pop operation.

Let me know if my code is good or bad.  You can be harsh.  I'll take it positively and learn from it.

typedef struct stack_ {
    int data;
    struct stack_ *next;
}stack;

stack *push(stack *head, stack **top, int val){
    //if stack is empty
    if(head == NULL){
        head = (stack *)malloc(sizeof(stack *));
        head -> data = val;
        head -> next = NULL;
        *top = head; //make current node the top of stack
        return head;
    }

    stack *newnode;
    newnode = (stack *)malloc(sizeof(stack *));
    (*top)->next = newnode; //append new node to what top points to
    newnode -> data = val;
    newnode -> next = NULL;
    *top = newnode; //make current node the top of stack
    return head;
}

stack *pop(stack *head, stack **top){
    if(head == NULL){
        printf("Stack is empty\n");
        return NULL;
    }

    stack *cur, *prev;
    cur = head;
    while(cur -> next){ //Traverse to the end
        prev = cur;
        cur = cur -> next;
    }

    prev -> next = NULL;
    *top = prev; //make this node the top of stack
    free(cur);
    return head;
}

Here's the main function:

int main ()
{
    stack *head, *top;
    head = top = NULL;

    while(1){
        int choice;
        printf("1.Push\n2.Pop\n3.Exit\n");
        scanf("%d", &choice);

        if(choice == 3)
            break;
        else if(choice == 2){
            head = pop(head, &top);
            showstack(head);

        }
        else if(choice == 1){
            int val;
            printf("Enter the value to be pushed\n");
            scanf("%d", &val);
            head = push(head, &top, val);
            showstack(head);
        }
        else
            printf("Enter the correct choice\n");

    }
    if(head)
        free(head);
    if(top)
        free(top);
    return 0;
}


texts: Using a singleton for a collection of discounts to calculate?

texts:
I'm wondering if using a Singleton for a storage of discounts is the right way to go. This is because I will be looping over all added discounts in another class.

client code

// Dynamically add new Discounts
$collection = DiscountCollection::getInstance();
$collection->add(new TenPercentDiscount());
$collection->add(new TwentyPercentDiscount());

DiscountCollection

<?php namespace Notflip\Discount;

use Notflip\Discount\Discounts\Discount;

class DiscountCollection {

    private static $instance;
    private static $discounts;

    final static function getInstance()
    {
        if(static::$instance === null)
        {
            static::$instance = new static();
        }

        return static::$instance;
    }

    public function add(Discount $discount)
    {
        static::$discounts[] = $discount;
    }

    public function count()
    {
        return count(static::$discounts);
    }

    public function show()
    {
        return static::$discounts;
    }
}


texts: Javascript Fibonacci with dynamic programming

texts:
Trying to applying what seen on What Is Dynamic Programming and How To Use It (here: https://www.youtube.com/watch?v=vYquumk4nWw )
Obviuously this is the final code, after removing the recursion.
I thought it was a good idea to memoize just the latest two values instead of the whole sequence.
I could replace the array with two values and a temp one to make the shift but maybe it will affect readability.
What you think ?

fibonacci: function (n)
{
    if (n === 0 || n === 1) return 1;

    var array = [1, 1];

    for (var i = 2; i < n; i++) {
        array.push(array[0] + array[1]);
        array.shift();
    }

    return array[0] + array[1];
}


texts: Handling arguments in a Python-like range() function in JavaScript

texts:
I'm making a Python-like range() function (see Python docs) using JavaScript. This function can take from 1 to 3 arguments. There are 3 variables (start, stop and step) that need to have some value, either from arguments, or a default value.

If only one argument is passed, start is 0, stop is the first argument and step is 1.
If two arguments are passed, start is the first argument, stop is the second argument and step is 1.
If three arguments are passed, start is the first argument, stop is the second argument and step is the third argument.

I'm aware that since ECMAScript 6 JavaScript has default parameters, but the situation here is more complex. Therefore, I used rest parameters to get an array of all arguments and then assign them to appropriate variables.

const range = (...args) => {
  if (args.length < 1 || args.length > 3) {
    throw new Error('This function takes between 1 and 3 arguments')
  }
  const [start, stop, step] = {
    1: [0, ...args, 1]
   ,2: [...args, 1]
   ,3: args
  }[args.length]
}

I'm using the solution presented in the article Replacing switch statements with Object literals. The object keys are numbers of arguments and values are arrays with values for start, stop and step. I select the array which matches args.length and use destructuring assignment to assign the array elements respectively to start, stop and step.

This code is quite short, but I'm not sure whether it's readable. I came up with an alternative solution, using simple if-else blocks. I have to declare the variables at the beginning here, because let and const are block-scoped, so declaring them inside the if-else blocks would have no effect on the rest of the function.

const range = (...args) => {
  let [start, stop, step]
  if (args.length === 1) {
    ;[start, stop, step] = [0, ...args, 1]
  } else if (args.length === 2) {
    ;[start, stop, step] = [...args, 1]
  } else if (args.length === 3) {
    ;[start, stop, step] = args
  } else {
    throw new Error('This function takes between 1 and 3 arguments')
  }
}

This version maybe is more readable, but I don't like it very much. It repeats the [start, stop, step] fragment four times, and also I can't use const (and I'm trying to use const whenever possible).

Another solution that came to my mind is to assume as default the situation when two or three parameters are passed, and when one parameters is passed, assign start to stop and 0 to start.

const range = function(start, stop, step = 1) {
  if (arguments.length < 1 || arguments.length > 3) {
    throw new Error('This function takes between 1 and 3 arguments')
  }
  if (stop === undefined) {
    ;[start, stop] = [0, start]
  }
}

This also doesn't look good to me. I think that for someone reading this code it would be very difficult to understand what it does. Also, this code forces me to use a regular function instead of arrow function (because arrow functions don't have arguments) and violates two ESLint rules which I'm using: prefer-rest-params and no-param-reassign.

What is the best way to solve this problem? Should I modify one of the solutions that I already have, or should I try something completely different?

Edit

I made a variation of the third option which doesn't violate any of my ESLint rules:

const range = (...args) => {
  if (args.length < 1 || args.length > 3) {
    throw new Error('This function takes between 1 and 3 arguments')
  }
  let [start, stop, step = 1] = args
  if (stop === undefined) {
    ;[start, stop] = [0, start]
  }
}


texts:
I need a function call(f, args...) which calls the "function" f with the arguments args.... It should be compatible with the following "functions":

Normal function pointers functors, lambdas, ... (= "callables"), call syntax: f(args...)
Member function pointers, call syntax: (object.*f)(args...) and (ptr->*f)(args...)
Member data pointers, call syntax: (object.*f) and (ptr->*f)

In the latter two cases, the object is the first of the arguments given to call and the args... the remaining arguments given to call. Also, they should work with objects, pointers and smart pointers (for which I assume the smart pointer class implements operator* returning a T&, so I don't use the syntax ptr->*f but rather (*ptr).*f).

As I thought there is no such thing in the standard library (but I remember they have something similar, e.g. they have mem_fun as a wrapper which could be useful here), I wrote it by myself.

Currently, the member versions (2. + 3.) are only needed for const objects/pointers and const member function/data pointers.

// 1.
// Normal function call (also supports functors / lambdas)
template <class Fn, class ...Args>
auto call(Fn &&f, Args && ...args) -> decltype(f(std::forward<Args>(args)...)) {
    return f(std::forward<Args>(args)...);
}

// 2.
// Member function call on instance
template <class T, class Ret, class ...Args, class ...ProvidedArgs>
Ret call(Ret (T::*memFn)(Args...)const, const T &x, ProvidedArgs && ...args) {
    return (x.*memFn)(std::forward<ProvidedArgs>(args)...);
}
// Member function call on dereferenced raw pointer
template <class T, class Ret, class ...Args, class ...ProvidedArgs>
Ret call(Ret (T::*memFn)(Args...)const, const T *x, ProvidedArgs && ...args) {
    return ((*x).*memFn)(std::forward<ProvidedArgs>(args)...); // or ->*
}
// Member function call on dereferenced smart pointer
template <class T, class Ret, class SmartPtr, class ...Args, class ...ProvidedArgs>
Ret call(Ret (T::*memFn)(Args...)const, const SmartPtr &x, ProvidedArgs && ...args) {
    return ((*x).*memFn)(std::forward<ProvidedArgs>(args)...);
}

// 3.
// Member variable on instance
template <class T, class Ret>
Ret call(Ret (T::*memVar), const T &x) {
    return (x.*memVar);
}
// Member variable on dereferenced raw pointer
template <class T, class Ret>
Ret call(Ret (T::*memVar), const T *x) {
    return ((*x).*memVar); // or ->*
}
// Member variable on dereferenced smart pointer
template <class T, class Ret, class SmartPtr>
Ret call(Ret (T::*memVar), const SmartPtr &x) {
    return ((*x).*memVar);
}

Is there something to be improved (performance-wise, usability-wise, ...)? Can you think of a different case of "functions" which can be useful to be supported by my call function?

My open questions about the current implementation are:

Is my use of universal references and std::forward correct to achieve "perfect forwarding" to the target function? In case 2., I'm not sure if I should put Args or ProvidedArgs in the template parameter of std::forward. I need two packs to be deduced separately for the function type and the parameters for the case they don't match (but can be converted).
Should the smart pointer parameter in cases 2. + 3. be a universal reference && or const&? Currently I use const&.
Should the function parameter in case 1. be a universal reference && or const&? Currently I use &&.


texts: Am I missing any security loopholes in this php script that reads and outputs directory/file from $_GET variable

texts:
Due to a weird server setup on one of my client's websites, I needed to setup a script to load referenced pdf files through a case-insensitive lookup.  We originally looked into mod_speling, but it was causing issues with other mod_rewrite declarations. I'm not entirely sure why, but I didn't have much control over those other declarations, since they had other people working on their site as well.

So anyway, they have a bunch of references to their PDF files all over the internet with a bunch of different capitalization. Realizing that getting all of these to switch over to the proper file name was gonna be nearly impossible, I opted to write a script to do the translation for me.

The script forces http://www.somedomain.com/somedirectory/subdirectory/anypdffile.pdf to load through my pdffiles.php file.

The script seems to work perfectly. I'm not too worried about server performance, as I don't think it's gonna be used all that often. I just wanted to get a second pair of eyes to make sure I didn't leave any major security loopholes in here since I'm reading a directory/file from a $_GET variable.

First I added this to the .htaccess file to redirect all pdf files to a php script

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_URI} \.pdf$ [NC]
RewriteRule (.*) pdffiles.php?p=$1

Then put the following code in the pdffiles.php file:

<?php

// shorthand for our docroot
$root = $_SERVER['DOCUMENT_ROOT'];

// get our filepath (correct format is "somedir/otherdir/xyz.pdf")
$path= $_GET['p'];

// Rule 1 - Don't allow empty path
if (!empty($path)) {
    // get the directory for our file
    $dir = dirname($root.'/'.$path);

    // get the filename
    $file = basename($path);

    // get our extension
    $ext = pathinfo($file, PATHINFO_EXTENSION);

    // Rule 2 - Don't allow direct access to the script
    if (!strstr($_SERVER['REQUEST_URI'], 'pdffiles.php')) {

        // Rule 3 - Ensure PDF extension
        if (strtolower($ext) == "pdf") {

            // Rule 3 - Make sure document root + path is a real path
            if (($dir = realpath($dir))) {

                // Loop through directory contents
                if ($fh = opendir($dir)) {
                    while (false !== ($tfile = readdir($fh))) {

                        // ignore the default directories
                        if ($tfile != "." && $tfile != "..") {

                            // convert both to all lower case and try to match
                            if (strtolower($tfile) == strtolower($file)) {

                                // if they match then go ahead and output file
                                header("Content-type: application/pdf");
                                readfile($dir.'/'.$tfile);
                                exit;

                            }
                        }

                    }
                }

            }
        }

    }
}

// we failed one of our checkpoints, redirect to 404
header("HTTP/1.1 301 Moved Permanently");
header("Location: /notfound.html");
?>


texts: C++ return the sum of the 2 smallest elements in a vector

texts:
Here is the description of the problem from codewars:

Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 integers. No floats or empty arrays will be passed.
For example, when an array is passed like [19,5,42,2,77], the output should be 7.
[10,343445353,3453445,3453545353453] should return 3453455.
Hint: Do not modify the original array.

And this is my solution which passed all tests.
// Returns the index of the smallest number.
int smallest(std::vector<int> numbers) {
  int smallest = 1;
  for(int i = 0; i < numbers.size(); i++)
  {
    if(numbers[i] < numbers[smallest]) {
      smallest = i;
    }
  }
  return smallest;
}

long sumTwoSmallestNumbers(std::vector<int> numbers)
{
  int firstIndex = smallest(numbers);
  uint64_t first = numbers[smallest(numbers)];
  numbers.erase(numbers.begin() + firstIndex);

  uint64_t second = numbers[smallest(numbers)];

  return first + second;
}

While it's fairly fast and simple I feel like there is a way to do it while only looping over the list once and the hint about not modifying it seems to suggest that.


texts:
app.js

var employees = require('../models/employees');

employees.read(req.params.id, function(body) {
    console.log(body.firstName);
});

models/employees

var request = require('request');

var employees = {

    read: function(id, callback) {
        request
            .get('http://api.mysite.com/employees/' + id, function(error, response, body) {
                body = JSON.parse(body);
                return callback(body);
            })
    },
};

module.exports = employees;

This works (returns the employee name correctly), but I'm not sure if this is the correct (async) way of getting data from an API and displaying it.


texts: PHP form validation and db insertion, one page or two

texts:
I have a PHP form that uses the POST method to get information from form to db. I have my form separate from the form validation and insertion page.

Here is my form:

<?php
//get the header and the navigation bar inside the page.
$page_title = 'Demographics';
include('php_includes/header.html');
?>

    <form class="form" action="insert_demographics.php" method="post" name="demographics" id="demographics">

Demographics

Medical Record Number / Visit ID (Number 17 Characters):

        <input class="form-control" id="mrn" name="mrn" type="text" maxlength="17">

Last Name:

        <input class="form-control" id="LastName" name="LastName" type="text" onfocus="emptyElement('status')" maxlength="75">

First Name:

        <input class="form-control" id="FirstName" name="FirstName" type="text" onfocus="emptyElement('status')" maxlength="75">

Social Security Number:

        <input class="form-control" id="SSN" name="SSN" type="text" onfocus="emptyElement('status')" maxlength="9">

    <button type="submit" id="demographicsbtn">Insert Demographics Data</button>

</form>

<?php
include('php_includes/footer.html');
?>

Here is my validation and insert page:

<?php
$page_title = 'Insert Demographics';
include('php_includes/header.html');

// Connect to the database
include_once("php_includes/db_connect.php");

// Gather the posted data into local variables
$mrn_demographics = mysqli_real_escape_string($db_connect, preg_replace('/[^a-zA-Z0-9]/', '', $_POST['mrn']));
$last_name        = mysqli_real_escape_string($db_connect, preg_replace('/[^a-zA-Z]/', '', $_POST['LastName']));
$first_name       = mysqli_real_escape_string($db_connect, preg_replace('/[^a-zA-Z]/', '', $_POST['FirstName']));
$ssn              = mysqli_real_escape_string($db_connect, preg_replace('/[^0-9]/', '', $_POST['SSN']));

// Get user IP Address
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));

// Form data error handling
if($mrn_demographics == "" || $last_name == "" || $first_name == "" || $ssn == ""){
echo "The form submission is missing data.";
exit();
} else {
// End form data error handling
$sql = "INSERT INTO nys_demographics (
    mrn,
    pt_last_name,
    pt_first_name,
    pt_ssn,
    ip_address,
    record_insert_dtime
)
VALUES('$mrn_demographics' ,'$last_name','$first_name','$ssn','$ip',
now())";
}

if (mysqli_query($db_connect, $sql)) {
  echo "
Demographics have been inserted successfully, you will be auto-directed to the Injury Details form.

";
  echo "MRN: $mrn_demographics
";
  echo "Last Name: $last_name
";
  echo "First Name: $first_name
";
  echo "SSN: $ssn
";
  echo "From IP Address: $ip
";
  echo "On " .date("Y-m-d") ." at " .date("h:i:sa");
  header("refresh:3; url=injury_details.php");
} else {
  printf("Error: %s\n", mysqli_error($db_connect));
}

include('php_includes/footer.html');
?>

I have a couple of questions:

Should my validation code be in a different PHP page or the same?
Could my validation be better and better written?

I want to echo out what has been input into the form.


texts: Finding nth Prime using Python and Sieve of Eratosthenes

texts:
I'm currently working through the Project Euler Problems using HackerRank to evaluate the code and I'm stuck on the 7th Problem.

"""
    By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

    What is the 10 001st prime number?

"""
import pytest

def find_primes(limit):
    nums = [True] * (limit+1)
    nums[0] = nums[1] = False

    for (i, is_prime) in enumerate(nums):
        if is_prime:
            yield i
            for n in range(i*i, limit+1, i):
                nums[n] = False

def find_n_prime(n):
    for i in range(n, (n*n)+1, n):
        primes = list(find_primes(i))
        if len(primes) >= n:
            return primes[n-1]

def test_find_n_primes():
    assert find_n_prime(2) == 3
    assert find_n_prime(3) == 5

    assert find_n_prime(10) == 29
    assert find_n_prime(15) == 47
    assert find_n_prime(81) == 419

    assert find_n_prime(941) == 7417
    assert find_n_prime(1000) == 7919

    assert find_n_prime(10001) == 104743

The code only completes the first test case on hackerRank and fails for #2 test case and times out for the rest.

How can I improve the Code ?


texts:
I need to merge eve/odd rows on a data set.

Example:

      match team count points
    1     1  ARG    11     21
    2     1  ENG     9     19
    3     2  CAN     8     15
    4     2  USA     8     17
    5     3  FRA     7      7
    6     3  NZL     8     36

To:

      match team1 t1p t1s team2 t2p t2s
    1     1   ARG  11  21   ENG   9  19
    2     2   CAN   8  15   USA   8  17
    3     3   FRA   7   7   NZL   8  36

This is my current solution:

odd <- all_scores[seq(1, nrow(all_scores), 2),]
colnames(odd) <- c("match", "team1", "t1p", "t1s")
even <- all_scores[seq(2, nrow(all_scores), 2),]
colnames(even) <- c("match", "team2", "t2p", "t2s")
new_scores <- merge(odd, even)

Is there an easier, more space efficienct, or more R-like way to do this?


texts:
I have this method here called SubmitProc which submits form data that the user filled out to the server side and does a check if the response to the server goes through. If it's fine, great. If not, return the status error from the server. The data actually gets sent to SharePoint (not sure if it's politically correct to say it goes to server side if it goes to SP) but that's the idea.

If an exceptions results, then check if the files upload match the current procedure file count. If yes, do nothing, otherwise there is an error.

public async Task<string> SubmitProc(PFormData formData)
{
    Proj.Repositories.Models.External.Proc proc = formData.ProcForm;
    try
    {
        string url = Config.BaseAPIUrl;
        url = url + "AddPProc";

        string authToken = await Authentication.GetAuthToken();

        _client.DefaultRequestHeaders.Accept.Add (new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue ("application/json"));
        _clientHandler.CookieContainer.Add (new Uri (url), new System.Net.Cookie ("FedAuth", authToken));

        Proj.Repositories.Models.External.ProcResponse serviceResponse = await submitForm (url, proc).ConfigureAwait (false);

        if (serviceResponse.StatusCode == 200)
            return null;
        else
            return serviceResponse.StatusDescription;
    }
    catch (WebException ex)
    {

    }
    catch (Exception ex)
    {
    }

    try
    {
        if (proc.File != null)
        {
            int filesCount = await getUploadFilesCount ("Foo", proc.UniqueId);
            if (proc.File.Count == filesCount)
                return null;
            else
                return "Encountered error uploading attachments.";
        }
    }
    catch (Exception ex)
    {

    }

    return "Encountered unknown error.";
}

Where getUploadFilesCount is:

private async Task<int> getUploadFilesCount(string type, string guidString)
{
    try
    {
        string url = Config.BaseAPIUrl;
        url = url + "/VerifyUpload/" + type + "/" + guidString;// + "/" + {*procDate};

        string authToken = await Authentication.GetAuthToken ();

        _client.DefaultRequestHeaders.Accept.Add (new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue ("application/json"));

        _clientHandler.CookieContainer.Add (new Uri (url), new System.Net.Cookie ("FedAuth", authToken));

        HttpRequestMessage request = new HttpRequestMessage (HttpMethod.Get, url);
        HttpResponseMessage response = await _client.SendAsync (request);

        Proj.Repositories.Models.External.ProcResponse procResponse = JsonConvert.DeserializeObject<Proj.Repositories.Models.External.ProcResponse> (await response.Content.ReadAsStringAsync ());

        if(procResponse != null)
            return procResponse.FilesCount;

        return 0;
    }
    catch(Exception)
    {

    }

    return 0;
}

It's been working so far but the code above looks terrible. I'm maintaining this project and I just looked at this code and it definitely looks like it needs to be refactored but I'm afraid of breaking it. Any recommendations or advice on condensing this code or refactor it?

This code is currently inside a Xamarin.iOS App.


texts: Remove array items in an array in a CouchDB document

texts:
In this project I'm working with NoSQL databases (couchdb) and Node.JS using ES7 (via Babel).

This is my code to remove items from an array of addresses in a JSON document. If you see something that could be improved let me know:

  serviceInstance.removeAddress =  async function(groupId, index) {

    try {

      var currentDoc = await  serviceInstance.get(groupId)
      const addresses = currentDoc.addresses || []
      if(addresses.length) {
        var patchedDoc = await serviceInstance.patch(groupId, {
          addresses: addresses.splice(index, 1)
        })
      }
      return addresses

    }catch(err){
      return err
    }
  }


texts: Euler Project 14 - Longest Collatz Sequence in PHP

texts:
This is my solution to Project Euler 14:

  The following iterative sequence is defined for the set of positive integers:

n → n/2 (n is even)
n → 3n + 1 (n is odd)

  Using the rule above and starting with 13, we generate the following sequence:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

  It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

  Which starting number, under one million, produces the longest chain?

  NOTE: Once the chain starts the terms are allowed to go above one million.

<?php
$count = 0 ;
$max = 0;

for($n = 2 ; $n < 1000000 ; $n++){
    while ($n > 1)
    {
        if ($n % 2 == 0 )
        {
            $n = $n/2;

        }
        else
        {
            $n = 3*$n + 1 ;

        }
        $count += 1;

       if($count > $max )
       {
            $max = $count;
            $final = $n;
       }
    }
 }
 echo $final;
?>

It took so long to run. I looked at some other solutions and they were very similar to my code logically, but they were running way much faster than mine. My question is, what is it that makes my code inefficient?


texts: SQL stored procedure for fruit checks with several joins

texts:
I developed a SQL stored procedure which works lovely, but when under stress, it takes more than 2 minute to get back to the user. I am providing the stored procedure but would also provide the table structure if required.

/* Stored procedure to get fruits checks that the user has access to*/
ALTER procedure [dbo].[Fruits_GetChecksForUser]
(
    @UserID VARCHAR(200),
    @CheckUrlFilter varchar(256)
)
AS

SELECT Distinct
    Fruits_Checks.*,
    ManagementCommittees.Title As CommitteeName,
    FruitCategories.ID As CategoryID,
    FruitCategories.Title As CategoryName,
    dbo.IsUserInGroup(@UserID, FruitCategories.FruitOfficerGroupID) AS IsUserFruitOfficer,
    dbo.IsUserInGroup(@UserID, Fruits_Checks.AllocatedGroup) AS IsUserCheckResponsible,
    Policies.CompanyID,
    Policies.ID As PolicyID

FROM Groups_UserAccess
INNER JOIN FruitCategories_GroupAccess ON FruitCategories_GroupAccess.GroupID = Groups_UserAccess.GroupID
INNER JOIN FruitCategories ON FruitCategories.ID = FruitCategories_GroupAccess.FruitCategoryID
INNER JOIN Policies ON Policies.ID = FruitCategories.PolicyID
LEFT JOIN Policies_AppSettings ON Policies_AppSettings.PolicyID = Policies.ID
LEFT JOIN Clients_AppSettings ON Clients_AppSettings.ID = Policies.CompanyID
FULL OUTER JOIN Fruits ON Fruits.CategoryID = FruitCategories.ID
INNER JOIN Fruits_Checks ON Fruits_Checks.FruitID = Fruits.ID
INNER JOIN ManagementCommittees on Fruits_Checks.CommitteeID = ManagementCommittees.ID

WHERE
    Fruits.ID IS NOT NULL
    AND Fruits_Checks.URL LIKE '%' + @CheckUrlFilter + '%'

ORDER BY Fruits_Checks.EndDate


texts: Linear regression on points specified by the user in a GUI

texts:
Here's my take on the Linear Regression exercise from John Zelle's Python book.

  Open a window, let the user click on as many points as they want. Upon pressing the "Done" button the regression line of those points is drawn.

from graphics import *

def dots(win):
    sumx = 0
    sumy = 0
    sumx2 = 0
    sumxy = 0
    count = 0

    click = win.getMouse()
    clickX = click.getX()
    clickY = click.getY()

    while (clickX < 31 or clickX > 39 or
                clickY < 1 or clickY > 5):
            sumx += clickX
            sumy += clickY
            sumx2 += clickX**2
            sumxy += clickX*clickY
            count += 1

            Point(clickX, clickY).draw(win)

            click = win.getMouse()
            clickX = click.getX()
            clickY = click.getY()

    return sumx, sumy, sumx2, sumxy, count

def mean(sum, count):
    mean = sum / count
    return mean

def calcreg(sumx, sumy, sumx2, sumxy, count):
    xleft = 0
    xright = 40

    m = (sumxy - count * mean(sumx, count) * mean(sumy, count)) / (sumx2 - count * mean(sumx, count)**2)

    yleft = mean(sumy, count) + m * (xleft - mean(sumx, count))
    yright = mean(sumy, count) + m * (xright - mean(sumx, count))

    return Line(Point(xleft, yleft), Point(xright, yright))

def main():
    win = GraphWin("Regression Line", 400, 400)
    win.setCoords(0, 0, 40, 40)

    Text(Point(35, 3), "DONE").draw(win)
    Rectangle(Point(31, 1), Point(39 ,5)).draw(win)

    sumx, sumy, sumx2, sumxy, count = dots(win)

    try:
        regline = calcreg(sumx, sumy, sumx2, sumxy, count)
        regline.draw(win)
    except ZeroDivisionError:
        Text(Point(20, 20), "Enter at least 2 points!").draw(win)

    win.getMouse()

main()

Any tips on what I should/could change here?


texts:
I'm developing a win forms application in MVP pattern. In the application, there is a small module to show the branch offices (called points) where the attendance entering process has been completed. Those details should be shown in a data grid view.

So I have a form (View), a presenter and a data service classes. For the simplicity I'm not using a "model class" for this as the only intended functionality is populating the grid view.

Form frmAttendancePoints and DataService class have implemented  IAttendancePointsView and IDataService interfaces respectively.

My question: Is the way I'm populating the grid correct? If not could you please let me know a better solution.

View

public partial class frmAttendancePoints : Form, IAttendancePointsView
{
        private void frmEnterAttendance_Load(object sender, EventArgs e)
        {
            ShowAttendancePoints(sender, e);
        }

        public void LoadAttendacePointsGridWithData(DataTable dt)
        {
            dgAttendancePoints.DataSource = dt;
        }

        public event EventHandler ShowAttendancePoints;
}

Presenter

class AttendancePointPresenter : BasePresenter
{
    IAttendancePointsView _View;
    IDataService _ds;

    public AttendancePointPresenter(IAttendancePointsView View, IDataService ds)
    {
        _View = View;
        _ds = ds;
        WireUpViewEvents();
    }

    private void WireUpViewEvents()
    {
        this._View.ShowAttendancePoints +=new EventHandler(_View_ShowAttendancePoints);
    }

    private void _View_ShowAttendancePoints(object sender, EventArgs e)
    {
        ShowAttendancePoints();
    }

    private void ShowAttendancePoints()
    {
        var dt = _ds.GetAttendancePoints();
        this._View.LoadAttendacePointsGridWithData(dt);
    }

    public void Show()
    {
        _View.ShowDialog();
    }
}

DataService

public class DataServie
{
        public DataTable GetAttendancePoints()
        {
            string selectStatement = "SELECT PID, point_name + ', ' + point_add AS point, area, sm, atten_status FROM Point WHERE Status='Active'";
            using (SqlConnection sqlConnection = new SqlConnection(db.GetConnectionString))
            {
                using (SqlCommand sqlCommand = new SqlCommand(selectStatement, sqlConnection))
                {
                    using (SqlDataAdapter da = new SqlDataAdapter(sqlCommand))
                    {
                        using (DataSet ds = new DataSet())
                        {
                            using (DataTable dt = new DataTable())
                            {
                                ds.Tables.Add(dt);
                                sqlConnection.Open();
                                da.Fill(dt);
                                return dt;
                            }
                        }
                    }
                }
            }
        }
}

Programme

    IAttendancePointsView AttendancePointView = new frmAttendancePoints();
    IDataService ds = new DataService();

    var Presenter = new AttendancePointPresenter(AttendancePointView, ds);
    Presenter.Show();


texts: Menu and SideBar Slides, Fades, and Hides

texts:
I will admit that this code looks sloppy and repetitive. Which is why I'm asking how I can improve the efficiency and readability of this code.

// Sidebar tab highlight when clicked
$("#sidebar-tabs-container table td").click(function() {
  $("#sidebar-tabs-container table td").removeClass("sidebar-tab-selected");
  $(this).addClass("sidebar-tab-selected");
});

// poll and faq
// when faq question bar is clicked, slide down answer
$(document).on("click", ".question-container", function() {
$(".answer-container").stop().slideUp("fast");
$(this).parent().find(".answer-container").stop().slideToggle("fast");
});

// news and social feed

// activity
// activity new media content
//media buttons click
$(document).on("click", "#activity-media-icons-container span", function() {
    $("#activity-media-icons-container span").removeClass("activity-new-media-icon-  clicked");
$(this).addClass("activity-new-media-icon-clicked");
});

// show new media category and hide others depending on button clicked
$(document).on("click", "#new-media-images-button", function() {
   $("#activity-media-video-container, #activity-media-audio-container").slideUp(    function() {
   $("#activity-media-images-container").slideDown();
   });
});

$(document).on("click", "#new-media-videos-button", function() {
$("#activity-media-audio-container, #activity-media-images-container").slideUp( function() {
    $("#activity-media-video-container").slideDown();
});
});

$(document).on("click", "#new-media-audio-button", function() {
$("#activity-media-images-container, #activity-media-video-container").slideUp( function() {
    $("#activity-media-audio-container").slideDown();
});
});

/* show image link icon when hovered over image */
$(document).ajaxComplete(function() {
$(".media-image-buttons-container").hide();
});
// fade in image buttons on hover
$(document).on("mouseenter", "#media-content-container .media-image-container", function() {
$(this).children(".media-image-buttons-container").stop().fadeIn(200);
});
$(document).on("mouseleave", "#media-content-container .media-image-container", function() {
$(this).children(".media-image-buttons-container").stop().fadeOut(200);
});


texts: Fetch and display products from a SOAP call

texts:
I'm relatively new to php and any advice is appreciated.

I retrieve some data from an external source and process them in a foreach loop to display the items. Now I'm not sure if the way I choose is the right way or if there is a better way for a situation like this.

And here the code I use:

define ("WSDL_SERVER",
"XXX");
$oSmartFeed= new SoapClient(WSDL_SERVER);
$oSessionHash= $oSmartFeed->login('XXX', 'XXX');
if(!$oSessionHash->HasError){
$sSessionHash= $oSessionHash->Records['sessionHash'];
$aConfig= array('limit'=>5, 'offset'=>2, 'feeds'=>[XXX]);
$aResult= $oSmartFeed-> getProductData ($sSessionHash, $aConfig);

echo '
';

foreach ($aResult->Records AS $aRecord) {

    $produktName = $aRecord['productname'];
    $imageUrl = $aRecord['imagebigurl'];
    $price = $aRecord['currentprice'] . $aRecord['currency'];
    $affLink = $aRecord['deeplinkurl'];
    $productDescription = $aRecord['productdescriptionlong'];
    $versandKosten = $aRecord['shipping'] . ' €';

    ?>

           <a href="<?php echo $affLink;?>">
               <img src="<?php echo $imageUrl; ?>" alt="<?php echo $produktName; ?>">

                   <?php echo $produktName; ?>

                   <?php echo $productDescription;?>

                       Price: <?php echo $price; ?>

                       Shipping: <?php echo $versandKosten; ?>

    <?php
}
echo '
';
$oSmartFeed->logout($sSessionHash);


texts:
I am working on an XNA project, and since procedural generation is likely to be used, I wanted to eventually create a helper class to work with data to facilitate that.

Design Goal:

Originally, I wanted to generate and modify a heightmap in a simple but efficient manner. The most straightforward approach to handle this would be a with a float[,].

Right now, I have a Grid<T> which simply holds the data in a more convenient manner, but I want to introduce a way to transform it somehow - slicing, rotations, etc. The ability to add and multiply different heightmaps together would be beneficial as well.

My Code:

Knowing that C# is optimized for single-dimensional arrays, I decided to make a simple wrapper class that contains an internal jagged array, but have it look and behave like a 2-dimensional array.

I first made it into an interface because doing so allows me to implement it however I want, which allows for future optimizations which won't break any dependent code:

// Presents itself as a simplified 2-dimensional array
public interface IGrid<T> : IEnumerable<T>, IEnumerable
{
    Point Size { get; }
    T this[int x, int y] { get; set; }
}

And the current (simplified) implementation is:

// Functions as a jagged array under the hood
public class Grid<T> : IGrid<T>
{
    private readonly T[][] _values;

    // Implement IGrid<T>
    public Point Size { get; private set; }
    public T this[int x, int y]
    {
        get { return _values[y][x]; }
        set { _values[y][x] = value; }
    }

    // Constructor
    public Grid(int x, int y)
    {
        Size = new Point(x, y);
        _values = new T[y][];
        for (int i = 0; i < y; i++)
            _values[i] = new T[x];
    }

    // Provide IEnumerator, override ToString(), etc...
}

My approach for the transformation bits is similar:

public interface ITransformable<T>
{
    T Slice(int x, int y, int width, int height);
    T Slice(Rectangle value);
    T Transpose();
    T Flip(bool horizontal, bool vertical);
    T Rotate(bool clockwise);
}

And here is where I am stumbling. I'm not actually sure what I want to do with it!

Attach it to IGrid<T>. It's no longer about simply storing the data, but transforming it as well.
Attach it to Grid<T>. The fact that a grid can transform the data is an implementation detail.
Create a derived class Mesh<T> which does everything Grid<T> does, but also implements ITransformable<T>.
Create a derived class Mesh<T>, but remove ITransformable<T> and move its methods into this class.

Thoughts:

Since generic types do not support operator overloading (+, -, /, *), it means that if I want a Heightmap to support addition in the form of Heightmap m = a + b, it would need a specific implementation, such as public class Heightmap : Mesh<float>, which then supplies the implementation of the operators.

Based on that, my entire class chain might resemeble:

public interface IGrid<T> { ... }
public interface IMesh<T> : IGrid<T> { ... }
public class Grid<T> : IGrid<T> { ... }
public class Mesh<T> : Grid<T>, IMesh<T> { ... }
public class Heightmap : Mesh<float> { ... }


texts: Function to get the ratio of the number of positive, negative, and null values inside an array in relation to its length

texts:
I wrote a function that checks what's the ratio of the number of positive, negative and null values inside an array in relation to its length.
The code I wrote is the following:

function plusMinus(arr) {

    /**first I declare 3 variables to store the positive, negative and null elements inside them*/

    let numPositive = [];
    let numNegative = [];
    let numZero = [];

    /**then I write a loop that will check whether
    the elements of the input array are positive, negative or null,
    e.g. if the element[i] is positive, then the array
    numPositive pushes the positive element[i] inside it,
    and so on for the rest of the numbers and arrays*/

    for (let i=0; i<arr.length;i++){
        if (arr[i]>0){
            numPositive.push(arr[i]>0);
        }else if (arr[i]<0){
            numNegative.push(arr[i]<0);
        }else{
            numZero.push(arr[i]==0)
        }
    }

    /**finally, the ratios are given as a result of
    the length of the pushed arrays and the length of the original array*/

    console.log(numPositive.length/arr.length);
    console.log(numNegative.length/arr.length);
    console.log(numZero.length/arr.length);
}

I'd like receive some feedback on why my code's logic doesn't work.


texts:
I'm currently working on CSRF prevention and I would love to hear your feedback for my code. I assume that there are no XSS vulnerabilities in order for the CSRF protection to work. Furthermore, I assume that all state-changing/critical actions are done via post-requests. One token is generated per session.

Here is the code:

<?php

/*
 * CSRF prevention module
 */

class CSRF {

    private static $key = "token";

    public static function init() {
        if (session_status() === PHP_SESSION_NONE)
            die("[CSRF::init] PHP session engine is not started");

        if (!self::has_tok())
            self::set_tok(self::gen_tok());
    }

    public static function inject_token() {
        if (!self::has_tok())
            die("[CSRF::secure_form] There is no token");

        echo "<input type='hidden' name='" . self::$key
           . "' value='" . self::tok() . "'>\n";
    }

    public static function valid_post() {
        $src = parse_url(self::source_origin(), PHP_URL_HOST);
        return $src === $_SERVER['SERVER_NAME']
            && isset($_POST[self::$key])
            && self::match_tok($_POST[self::$key]);
    }

    private static function gen_tok() {
        return base64_encode(random_bytes(64));
    }

    private static function has_tok() {
        return isset($_SESSION[self::$key]);
    }

    private static function set_tok($tok) {
        $_SESSION[self::$key] = $tok;
    }

    private static function match_tok($tok) {
        return self::has_tok() && $tok === self::tok();
    }

    private static function tok() {
        return $_SESSION[self::$key];
    }

    private static function source_origin() {
        if (isset($_SERVER['HTTP_ORIGIN']))
            return $_SERVER['HTTP_ORIGIN'];
        if (isset($_SERVER['HTTP_REFERER']))
            return $_SERVER['HTTP_REFERER'];
        return "";
    }
}

?>

Usage example:

 <form action="foo.php" method="post">
     <?php CSRF::inject_token(); ?>
     ...
 </form>

And then in foo.php:

<?php
    ...
    if (!CSRF::valid_post())
        die("CSRF");
    ...
?>

Any suggestions for improvements? Did I miss anything? I know adding the tokens to forms could be automated with javascript (there is an OWASP CSRF Protection module), but I prefer to have a site that can run without javascript. I don't plan on having too many forms, so I think I can manage to not forget securing one.

I recently added checking the origin/referer after reading OWASP CSRF Prevention Cheat Sheet, but I'm not sure I did it properly.

EDIT: I just realized from the code example at OWASP that

(1) I should compare protocol and port, too, not just the host.


texts: Server which writes to mongo and makes http request

texts:
This is simple server which basically just writes something to mongo after it accepts POST request, and then initiates a new HTTP request.
I would appreciate feedback especially if I am doing correctly error handling etc.
The code does its job though.

const MongoClient = require('mongodb').MongoClient;
const express = require('express')
const app = express()
var bodyParser = require('body-parser');
var http = require('http');

/* Connection URL */
const URL = 'mongodb://localhost:27017';

/* Database Name */
const DB_NAME = 'config-insert';

/* Handle to the connection */
let db = null;

/* Middlewares */
app.use(bodyParser.json());

/*
 * Use connect method to connect to the server
 */
MongoClient.connect(URL, function (err, client) {
    if (err) {
        throw new Error("Error connecting to mongo");
    }

    db = client.db(DB_NAME);

});

/*
 * Insert one document to mongo database.
 *
 * Parameters
 *   data - what to insert.
 *   successCallback - success callback.
 *
 */
function insertOne(data, successCallback) {

    if (!db) {
        throw new Error("There is no connection");

    }

    /* Insert a single document */
    db.collection('config-history').insertOne(data, {
        w: 'majority'
        , wtimeout: 10000
        , serializeFunctions: true
    }, function (err, r) {

        if (err) {
            throw new Error("Error inserting");

        }

        successCallback(r);

    });
}

/*
 * Handler for post request
 */
app.post('/', function (req, res) {

    let data = req.body;

    insertOne(JSON.parse(JSON.stringify(data)) /* use this otherwise mongo was modifying data variable */, function success() {

        let req = http.request({
            host: '10.1.1.41',
            path: `/category/${data.id}`,
            method: 'PUT',
            port: 9202
        }, function (response) {

            var resp = '';
            response.on('data', function (d) {
                resp += d;
            });
            response.on('end', function () {
                if (JSON.parse(resp)._shards.successful == 1) {
                    res.status(200).json({ status: "ok" })
                }

            });

        });

        req.on('error', (e) => {
            console.error(`problem with request: ${e.message}`);
        });

        req.write(JSON.stringify(data));
        req.end();

    })

})

/*
 * Listen for connections.
 */
app.listen(4000, () => console.log('Example app listening on port 4000!'))