texts: Is the use of Struct or Class personal preference?

texts:
I have a solution in which I instantiate a class with various types inside of it.  I feel it is becoming to cumbersome to instantiate and then create  variables for each of the types I want to access in the class (Option 2 in the code), so I've come up with a custom return type so I only have to return data once for use (option 1).

So with the struct my code is more readible in the MAIN block, but is there a better way to do this?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace retclass
{
    class Program
    {
        static void Main(string[] args)
        {

            //Option 1 Struct and function
            //create struct
            ret x = new ret();
            x = goofie(3, "this is the struct string");
            Console.WriteLine("The String is {0}, the int is {1} and the value is {2}", x.str, x.num, x.yesno);

            //Option 2 Class
            //Instantiate retclass
            retclass retins = new retclass();
            retins.num = 3;
            retins.str = "this is the class string";
            if ((retins.num > 0) && retins.str != "")
            {
                retins.yesno = true;
            }
            Console.WriteLine("The String is {0}, the int is {1} and the value is {2}", retins.str, retins.num, retins.yesno);
            Console.ReadLine();

        }

        public struct ret
        {
            public int num { get; set; }
            public string str { get; set; }
            public bool yesno { get; set; }
        }

        public static ret goofie(int isn, string ss)
        {
            ret dex = new ret();
            dex.str = ss;
            dex.num = isn;
            if ((dex.str != "") && (dex.num > 0))
            {
                dex.yesno = true;
            }
            return dex;
        }
    }

    public class retclass
    {
        public int num { get; set; }
        public string str { get; set; }
        public bool yesno { get; set; }
    }

}


texts: Scrolling event being fired too many times

texts:
This code works and does the job, but it's poor, rudimentary and has some issues with the scrolling event. Can somebody help me to optimize the scrolling event?
Prototype
Structure and desired behaviour:

There are two containers, .layout__left (red) and .layout__right (green).
The green container will have the main content and will scroll normally.
The red container will have the navigation so it will have less content and should scroll up to a certain point only, until the menu reaches the border of the page.

This is what I am doing:

First both containers scroll normally.
When scrolling down the red container, if the scroll position + window size is bigger than the li:last child position (couldnt think of anyway to detect the "bottom"), then the container has a position fixed.
When scrolling up, the fixed position is disabled and when the menu reaches the top of the document, the position is fixed again, and then removed.

As I said, it does the job, but, it's slow and has glitches while scrolling. I think it's because I am doing on the scroll event on every pixel change.
I tried throttling the function call, but the code doesn't function at all:
    $(window).on('scroll', function() {
    $.throttle(100, sectionScroll));
    });

    sectionScroll = function() {
    var lastScrollTop = 0, delta = 5;
    var left = $('.layout__left');
    var right = $('.layout__right');
    var scroll = $(this).scrollTop();
    var viewport = $(window).height();
    var lastChild = $('.navigation > ul > li:last-child').offset().top;

    if(Math.abs(lastScrollTop - scroll) <= delta)
    return;

    if (scroll > lastScrollTop){
    // SCROLL DOWN
    left.removeClass('top absolute');

    // if the last item of the left is visible
    if (  (scroll + viewport) > (lastChild + 30)  ) {
    // make the left fixed
    left.addClass('fixed bottom');
    console.log("bottom!");
    }

    // SCROLL UP
    } else {
    // remove fixed class from left
    left.removeClass('fixed bottom');
    left.addClass('absolute bottom');

    if ( scroll <= left.position().top   ) {
    left.removeClass('bottom absolute');
    left.addClass('top fixed');
    left.removeClass('top fixed');
    console.log("top!");
    }
    }

    lastScrollTop = scroll;
    };

Any feedback?


texts:
In a recent project I was to create a web service that would be consumed by another application. One of the requirements was to have a key in the service that authenticated the request as valid. But this key must never be the same and the key should be invalid soon after its use.

This is the code I wrote to that purpose.

public static bool isKeyValid(long testKey)
{
    var k = GetKey();

    var allowedVariance = 0.00000000004;
    var variance = k * allowedVariance;

    return (k + variance >= testKey && k - variance <= testKey);
}

public static long GetKey()
{
    var i = (long)DateTime.UtcNow.Ticks * 5;
    var d = (long)Math.Sqrt(Math.Ceiling(400 - (DateTime.UtcNow.Day * Math.PI)));
    var k = (long)((Math.Round((Math.Sqrt(i) * Math.Pow(Math.PI + d, 3)) * Math.E - d)) * d) + DateTime.UtcNow.Minute;
    return k;
}

The point being that the caller generates a key and the receiver generates its own and then compares these two and says everything is ok if the difference is within a given variance.

Note that nothing in the message is really secret and this is just a simple check so that the request is probably from a valid source.

I have two questions for this.

How could I have done this better in terms of existing encryption
libraries (in .Net) or using other things such as certificates. This must work     cross platform (Windows, iOS, and Android devices)
How can the given code be modified or improved to make it better for
the intended purpose?


texts:
This is a problem from Codesignal.
The guaranteed constraints are 1 <= a.length <= 10^5, and 1 <= a[i] <= a.length.
You have to return the first duplicate encoutered in a, or -1 if no duplicate is found.
def firstDuplicate(a):

    b = [0] * 100001
    for num in a:
        if b[num] == 1:
            return num
        else:
            b[num] = 1
    return -1

Is there a better way to do this? Perhaps faster or using less memory? The unused 0 index in the b array also doesn't feel very clean.


texts:
I have an app that uses HTML5 video and our customer still needs to support IE8. Gross.

Anyway, I came up with this directive in Angular to for embedding a SWF for when I need to fallback to Flash. It works fine so far, but I would like to see if there is anything I can do to improve it. Can anyone see a case where this would fail? I am using Modernizr to detect if the browser supports video (Modernizr.video). If it doesn't if falls back and I load this directive.

The directive:

'use strict';

angular.module('flash-embed', []).directive('flashEmbed', [function()
{
  return {
    restrict: 'A',
    replace: true,
    template: ['',
     '<object data="{{src}}" type="application/x-shockwave-flash">',
        '<param name="allowscriptaccess" value="always" />',
        '<param name="allowfullscreen" value="true" />',
        '<param name="wmode" value="transparent" />',
      '</object>'
    ].join(''),
    scope: {
      width: '@',
      height: '@',
      src: '@'
    },
    compile: function(elem, attrs, transcludeFn)
    {
      return function link (scope, element, attrs)
      {
        scope.$watch('src', function(src)
        {
          element.append('<param name="movie" value="' + src + '" />');
        });
      };
    }
  };
}]);

Its usage:

<div flash-embed src="testpreso/flash/preloader.swf" width="966" height="600"></div>

EDIT
5/8/2015 update

I am having troubles using this in IE8. A client of mine needs IE8 support, booo. The error I am getting in IE8 is:

[Object Error]
description: "Invalid argument."
message:     "Invalid argument."
name:        "Error"
number:      -2147024809

It has to do with the object tag I believe. I found this thread that may shed some light on the issue: https://stackoverflow.com/questions/9150938/invalid-argument-in-ie-8-on-jquery-prepend-on-flash-objects

I will update if I figure this out


texts: LeetCode: Validate Binary Search Tree C#

texts:
I was struggling with this question for many times,
and I have solved it every time, because I understand the concept.
but I can never get to a good concise solution which is easy to follow.

In a coding interview I always choke when I see this question.

This is the best solution I was able to come up with.

Can the code be written even more simple and easier to follow?

using GraphsQuestions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TreeQuestions
{
    /// <summary>
    /// https://leetcode.com/explore/interview/card/top-interview-questions-easy/94/trees/625/
    /// </summary>
    /// check the iterative version with a stack as well
    /// https://leetcode.com/explore/interview/card/top-interview-questions-easy/94/trees/625/discuss/32112/Learn-one-iterative-inorder-traversal-apply-it-to-multiple-tree-questions-(Java-Solution)
    [TestClass]
    public class IsValidBSTtest
    {
        //   2
        //  / \
        // 1   3
        [TestMethod]
        public void ValidTree()
        {
            TreeNode root = new TreeNode(2);
            root.left = new TreeNode(1);
            root.right = new TreeNode(3);
            IsValidBSTclass temp = new IsValidBSTclass();
            Assert.IsTrue(temp.IsValidBST(root));
        }

        [TestMethod]
        public void NotValidTree()
        {
            TreeNode root = new TreeNode(5);
            root.left = new TreeNode(1);
            root.right = new TreeNode(4);
            root.right.left = new TreeNode(3);
            root.right.right = new TreeNode(6);
            IsValidBSTclass temp = new IsValidBSTclass();
            Assert.IsFalse(temp.IsValidBST(root));
        }

        /*
         *      10
         *      / \
         *     5   15
         *         /\
         *        6  20
         */

        [TestMethod]
        public void NotValidTree2()
        {
            TreeNode root = new TreeNode(10);
            root.left = new TreeNode(5);
            root.right = new TreeNode(15);
            root.right.left = new TreeNode(6);
            root.right.right = new TreeNode(20);
            IsValidBSTclass temp = new IsValidBSTclass();
            Assert.IsFalse(temp.IsValidBST(root));
        }
    }

    public class IsValidBSTclass
    {
        public bool IsValidBST(TreeNode root)
        {
            return Helper(root, null, null);
        }
        public bool Helper(TreeNode root, TreeNode minNode, TreeNode maxNode)
        {
            if (root == null)
            {
                return true;
            }
            if (minNode != null && root.val <= minNode.val || maxNode != null && root.val >= maxNode.val)
            {
                return false;
            }

            return Helper(root.left, minNode, root) && Helper(root.right, root, maxNode);
        }
    }
}


texts:
Problem statement
I need to generate numeronyms from a string, let's say qwerty as follows:
qwerty
q1erty
q2rty
q3ty
q4y

Code
Can this solution can be improved or if there's any better approach?

const str = 'qwerty';
const lastCharPos = str.length - 1;

str
  .split('')
  .map(
    (_, i) =>
      i !== lastCharPos &&
      console.log(`${str[0]}${i ? i : ''}${str.slice(i + 1, lastCharPos)}${str[lastCharPos]}`)
  );


texts: Better way to refer to common elements in a sequence of objects?

texts:
I just posted this code in SO and one person said my code sucked, and that I should post it here. So here it is (with fix I asked for included, so you don't have to worry about that).

The main concerns that I have with it myself is how I iterate through a sequence of objects that the object itself is in. Apparently id is bad, because it's like id(). Someone also mentioned that I shouldn't make members of a collection overly aware of their own collection.

    import random

    class Car:
        def __init__ (self, company, doors, id):
            self.company = company
            self.doors = doors
            self.id = id

        def printDoors(self, id):
            print 'Car ' + `self.id` + ' has ' + `self.doors` + ' doors.'

        def findSameDoors(self, id):
            for i in self.company.cars:
                if self.id != i.id and self.doors == i.doors:
                    print 'Car ' + `i.id` + ' does too!'

    class Company:
        def __init__ (self, types):
            self.types = types
            self.cars = []

        def typesToNum(self):
            result = []
            for i in self.types:
                if i == 'sedan':
                    result.append(4)
                elif i == 'convertible':
                    result.append(2)
                else:
                    result.append(0)
            return result

    porsche = Company(['sedan', 'convertible'])
    honda = Company(['sedan', 'convertible', 'motorcycle'])

    for i in range(10):
        porsche.cars.append(Car(porsche, random.choice(porsche.typesToNum()), i))

    for i in range(10):
        honda.cars.append(Car(honda, random.choice(honda.typesToNum()), i))

    porsche.cars[0].printDoors(0)
    porsche.cars[0].findSameDoors(0)

Thanks for any pointers.


texts: Generic Pickle-Aware Super-Class for Mixing Classes with and without __slots__ in Python

texts:
I want a generic super-class that I can easily subclass - and if desired add slots to my class - without having to worry about any pickle issues (with the lowest protocol). Is this in general a good idea? And if so, is this class a good implementation?

class HasSlots(object):
    """Top-class that allows mixing of classes with and without slots.

    Takes care that instances can still be pickled with the lowest
    protocol. Moreover, provides a generic `__dir__` method that
    lists all slots.

    """

    # We want to allow weak references to the objects
    __slots__ = ['__weakref__']

    def _get_all_slots(self):
        """Returns all slots as set"""
        all_slots = (getattr(cls, '__slots__', [])
                         for cls in self.__class__.__mro__)
        return set(slot for slots in all_slots for slot in slots)

    def __getstate__(self):
        if hasattr(self, '__dict__'):
            # We don't require that all sub-classes also define slots,
            # so they may provide a dictionary
            statedict = self.__dict__.copy()
        else:
            statedict = {}
        # Get all slots of potential parent classes
        for slot in self._get_all_slots():
            try:
                value = getattr(self, slot)
                statedict[slot] = value
            except AttributeError:
                pass
        # Pop slots that cannot or should not be pickled
        statedict.pop('__dict__', None)
        statedict.pop('__weakref__', None)
        return statedict

    def __setstate__(self, state):
        for key, value in state.items():
            setattr(self, key, value)

    def __dir__(self):
        result = dir(self.__class__)
        result.extend(self._get_all_slots())
        if hasattr(self, '__dict__'):
            result.extend(self.__dict__.keys())
        return result

Thus, I can simply sub-class this without worrying about slots and pickle:

class MyClass(HasSlots):
    def __init__(self, x,y):
        self._x = x
        self._y = y

but later maybe I want to optimize it and simply add some slots:

class MySlotClass(HasSlots):
    __slots__ = ['_x', '_y']
    def __init__(self, x,y):
        self._x = x
        self._y = y

And I still want to guarantee that my new object can be pickled:

import pickle
pickle.loads(pickle.dumps(MyClass(1,2))
pickle.loads(pickle.dumps(MySlotClass(1,2))

Are there any serious issues with my idea and implementation? Is this: all_slots = (getattr(cls, '__slots__', []) for cls in self.__class__.__mro__) a good approach to take care that all slots are properly pickled?

Is the approach safe for sub-classes that reference each other in a circular fashion?


texts: Digit sum loops+random positive number generator

texts:
I have to prepare program that summing the digits of two given by user numbers and then give back the random number which is

natural number
the digit sum of this number is bigger then the digit sum of given by user numbers

It's look like everything is ok but i dont know if it is just luck in random number generator or it's working well.
Thank you for review.

import java.util.Random;

import java.util.Scanner;

public class Ex1 {

public static void main(String[] args) {
    Random rnd = new Random();
    Scanner scn = new Scanner(System.in);
    int sum1 = 0;
    int sum2 = 0;
    int sum3 = 0;
    int sum4 = 0;
    System.out.println("1TH NUMBER : ");
    int a1 = scn.nextInt();
    System.out.println("2ND NUMBER : ");
    int a2 = scn.nextInt();
    System.out.println((0 > a1 || 0 > a2 ? "ERROR-NEGATIVE NUMBER" : "OK"));
    while (a1 > 0) {
        sum1 += a1 % 10;
        a1 /= 10;
    }
    //System.out.println(sum1);
    while (a2 > 0) {
        sum2 += a2 % 10;
        a2 /= 10;
    }
    //System.out.println(sum2);
    int temp = sum1 + sum2; //temporary-for storage /=
    while (temp > 0) {
        sum3 += (temp) % 10;
        (temp) /= 10;
    }
    // System.out.println(sum3);
    while (true) {
        int a3 = rnd.nextInt(Integer.MAX_VALUE);
        sum4 += (a3) % 10;
        (a3) /= 10;
       // System.out.println(sum4);
        if (sum4 > sum3) {
            System.out.println(a3 + " this is my number");
            break;
        }
    }

}
}


texts:
I am working on some problems on Hackerrank.

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

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

  Input Format

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

  Output Format

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

  Constraints

  1 ≤ N ≤ 100

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

  Sample Input

3
abcdde
baccd
eeabg

  Sample Output

2

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

I solved the problem but I don't feel that it is fast or pythonic. I was wondering if someone could help me increase the performance and perhaps reduce the amount of memory being used.

numRocks = int(raw_input())
rockList = []
for x in xrange(numRocks):
    rock = raw_input()
    # list of sets()
    rockList.append(set(rock))
gemElement = 0
for x in rockList[0]:
    rocks = len(rockList) - 1
    count = 0
    for y in rockList[1:]:
        if x in y:
            count += 1
            if count == rocks:
                gemElement += 1
print gemElement


texts:
I have made a Query Builder, (not the full version of it yet) but I wanna ask if there is someone out there, there can improve this code even more. Will be nice to know so I can code the rest in the better way :)

<?php
class DB {

    private static $instance = NULL;

    public static function sql(){
        self::$instance = new self();
        return self::$instance;
    }

    // These methods set the query clauses
    // Use * as default
    public function select(string $select_options = "*") {

        $query_part = "SELECT ".$select_options;
        $this->select = $query_part;
        return $this;
    }

    // From table in DB
    public function from(string $from_options) {

        $query_part = "FROM ".$from_options;

        $this->from = $query_part;
        return $this;
    }

    // These methods set the query clauses
    public function where(string $where_options) {

        $query_part = "WHERE ".$where_options;
        $this->where = $query_part;
        return $this;
    }

    // GroupBy
    public function groupBy(string $group_options) {

        $query_part = "groupBy ".$group_options;
        $this->groupBy = $query_part;
        return $this;
    }

    public function get() {
        $array = (array)$this;
        $string = implode(" ", $array);

        return $string;
    }

}

And this I how it to call the query builder

// Use class DB
$query = DB::sql()
    ->select()
    ->from("CustomerInfo")
    ->where("customer_id > 300")
    ->get();

// Echo result
echo $query;


texts:
I made a closure-based PHP structure that behaves mostly like a classical object.
To change the object's state, one must derive a new copy by passing the altered state to the  newCounter() 'constructor'-function. If you alter $state inside a method without returning newCounter($state), the original object won't be affected because the 'method' closures have only a copy of $state.

function newCounter($state = NULL) {
    if(NULL === $state) {
        $state = [
            'counter' => 0,
            'name' => 'default_name'
        ];
    }
    /* private methods --> */
    $_round = function($number) {
        return round($number, 1);
    };
    /* public methods --> */
    $add = function($number) use ($state, $_round) {
        $state['counter'] += $_round($number);
        return newCounter($state);
    };
    $set_property = function($property_name, $value) use ($state) {
        $state[$property_name] = $value;
        return newCounter($state);
    };
    $get_property = function($property_name) use ($state) {
        return $state[$property_name];
    };
    /* expose the public api --> */
    return function($method, ...$args) use ($state, $add, $set_property, $get_property) {
        return ${$method}(...$args);
    };
}

The 'instance' then has something like a fluent interface:

$counter = newCounter()('add', 4)('add', 2.999)('set_property', 'name', 'MyCounter');
echo $counter('get_property', 'counter'); // --> 7
echo $counter('get_property', 'name'); // --> MyCounter

Nested structures are possible, too:

$nested_counter = $counter(
    'set_property',
    'sub',
    newCounter()('set_property', 'name', 'SubCounter')
);
echo $nested_counter('get_property', 'sub')('get_property', 'name'); // --> SubCounter

To change a nested component's state, one must use a workaround:

$nested_with_boo = $nested_counter(
    'set_property',
    'sub',
    $nested_counter('get_property', 'sub')(
        'set_property',
        'name',
        'Boo'
    )
);
echo $nested_with_boo('get_property', 'sub')('get_property', 'name'); // --> Boo

Does this structure qualify for an immutable object, and what do you think in general? Have you any Idea how I can enhance $set_property so I don't need this verbose workaround for changing a nested component?


texts: Accessing UserControl's DataContext from another UserControl

texts:
Given these classes:

public partial class MainPage : UserControl
{
    public MainPage()
    {
       InitializeComponent();
       //...

    }
}
public partial class LoginForm : StackPanel
{
   private LoginRegistrationWindow parentWindow;
   private LoginInfo loginInfo = new LoginInfo();
   public LoginForm()
   {
       InitializeComponent();
       //...
   }

   private void LoginOperation_Completed(LoginOperation loginOperation)
   {

    if (loginOperation.LoginSuccess)
    {
            // Here I need to access MainPages's DataContext property and set it with my ViewModel
    }
   }
}

I want to set MainPage's DataContext property inside LoginFrom. So I created the static instance of the MainPage class in the class itself:

public partial class MainPage : UserControl
{
    public static MainPage Instance { get; private set; }
    public MainPage()
    {
        InitializeComponent();
        Instance = this;
    }
}

Now I can access to the MainPage's DataContext this way:

MainPage.Instance.DataContext = new NotificationItemViewModel();

Now I'd like to hear your ideas about this kind of passing data between classes in a Silverlight application. Do you have any idea?

PS: actually I answered my original question here on Stackoverflow. But I'd like to hear your ideas in terms of code review.


texts:
I am writing the solution of Dijkstra's algorithm in JS. This is what has happened so far. I need to make it so that the choice of nodes is by recursion. Tell me how to do this better.

const size = 6;
сonst maxInt = 999999;
const graph = [
  [null, maxInt, 50, 20, maxInt, 30],
  [null, maxInt, maxInt, maxInt, 10, maxInt],
  [null, maxInt, 20, maxInt, 40, maxInt],
  [null, maxInt, maxInt, maxInt, maxInt, maxInt],
  [null, maxInt, 20, maxInt, 25, maxInt]
];

const nodeParams = (distance, path, visited) => {
  this.dist = distance;
  this.path = path;
  this.visited = visited;
};

let node = [];

for(let i = 1;i < size;i++) {
  node[i] = [];
  for(let j = 1;j < size;j++) {
    node[i][j] = nodeParams(maxInt, 0, false);
  }
};

const dijkstra = () => {
  for(let source = 1; source < size; source++) {
    node[source][source].dist = 0;
    let minNode, nextNode;
    for(let i = 1; i < size - 1; i++) {
      minNode = i === 1 ? source : nextNode;
      node[source][minNode].visited = true;
      nextNode = null;
      for(let w = 1; w < size; w++) {
        if (!node[source][w].visited) {
          if (node[source][minNode].dist + graph[minNode][w] < node[source][w].dist) {
            node[source][w].dist = node[source][minNode].dist + graph[minNode][w];
            node[source][w].path = minNode;
          }
          if(nextNode === null) {
            nextNode = w;
          }
        }
      }
    }
  }
};

dijkstra ();

let shortestPathString = '';

const getEachPathNode = (source, destination) => {
  if(destination != source && destination > 0) {
    getEachPathNode(source, array[source][destination].path);
    shortestPathString += ' ' + array[source][destination].path;
  }
}

const getShortestPath = (source, destination) => {
  shortestPathString = 'Самый короткий путь от ' + source + ' до ' + destination + ': ';
  if (array[source][destination].dist == maxInt) {
    shortestPathString += 'не связаны';
  } else {
    getEachPathNode(source, destination);
    shortestPathString += ' ' + destination;
  }

  shortestPathString += '.  Расстояние: ' + array[source][destination].dist;
  console.log(shortestPathString);
}

for(let i = 1; i < size; i++) {
  for(let j = 1; j < size; j++) {
    getShortestPath(i, j);
  }
}

If there are any comments on the code, I'll be very glad to hear them too. This code does not go into any project, I just just study programming and try to set myself tasks and solve them.


texts: Replacing elements from a list and its sublists - part II

texts:
This is sort of a follow-up to
Replacing elements from a list and its sublists
but now there are arbitrary numbers of words that would be replaced stored in a list.

Now write substitute2 that takes a list, a list of old words, and a list of new words; the last two lists should be the same length. It should return a copy of the first argument, but with each word that occurs in the second argument replaced by the corresponding word of the third argument:

source

Please review my code.

(define (substitute2 lst oldlst newlst)
    (define (maybe-swap elem oldlst newlst)
        (cond ((null? oldlst) elem)
            ((equal? (car oldlst) elem) (car newlst))
        (else (maybe-swap elem (cdr oldlst) (cdr newlst)))))
        (if (list? lst)
            (map (lambda (elem) (substitute2 elem oldlst newlst)) lst)
    (if (= (length oldlst) (length newlst)) (maybe-swap lst oldlst newlst) (error "invalid length"))))

How can I make this code better and more efficient? Did I overuse define?


texts:
I have some code to perform a redis lookup, but if the key to look up either doesn't exist or there's an issue connecting to Redis at all, it will use a default value.

The logic currently looks like this:

begin
 redis = Redis.new(:url => url)
 returned_value = redis.get(key)
 if returned_value == nil and defined?(default) != nil
   default
 else
   returned_value
 end
rescue Exception => e
  if default
    debug "Connection to redis failed with #{e} - Returning default value of #{default}"
    default
  else
    raise(Puppet::Error, "connection to redis server failed - #{e}")
  end
end

It feels like there might be a simpler way of doing this, right now this code feels a little wordy.

Any suggestions?


texts: Powershell function to get hash value of a file

texts:
I created a function to get the hash value of a file. Normally the output is 3 lines. My function does 3 things:

extracts the hash value
removes the spaces in between the hash value
prints hash value

Here is the output when using CertUtil -hashfile FILENAME.EXE SHA1

SHA1 hash of file FILENAME.EXE:
XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX
CertUtil: -hashfile command completed successfully.

My function:

function MyHash($file, $hashtype) {
    $hash = CertUtil -hashfile $file $hashtype
    $hashstring = $hash[1] -replace ' ',''
    echo $hashstring
}

my output:

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Am I ok calling commands such as CertUtil from within a function the way I am doing? Can the syntax and code be improved? I feel like I'm just throwing commands inside a function but it works.


texts: Function to return percentages in Python

texts:
I created a function for giving me percentages from two integers.  I want two decimal places in the result.

def percent(num1, num2):
    num1 = float(num1)
    num2 = float(num2)
    percentage = '{0:.2f}'.format((num1 / num2 * 100))
    return percentage

It works, but I doubt it's very pythonic (since I have no idea what I'm doing)

>> print percent(1234, 5678)
21.73


texts: Script to clean up old files that should only run one instance

texts:
I'm writing a bash script for deleting old files on a Linux server.  Here are some relevant facts about this script:

As currently written, it does work as expected.  However, it's entirely possible there's some edge case I haven't considered (which is part of my reason for posting here).
It will be run as root once a day, scheduled via cron.
Only one instance should run at a time.  If another instance is started, it should just exit.
It will delete any file whose mtime is over 30 days old, from the time of find's invocation.
Each run of the script will take a few hours.
The script will be running on a single CentOS 7 node, but it operates on a distributed file system exposed to hundreds of others.

Here is the actual script:

#!/usr/bin/env bash

NUM_PROCS=4
LIMIT_TIME=30 # days
PIDFILE="/tmp/cleanup.pid"
PID_NOW="$$"

function save-pid() {
    echo "$1" > "$PIDFILE"

    if [[ "$?" -ne 0 ]]; then
        # If we couldn't save the PID to the lockfile...
        echo "Failed to create PID file for PID $1 in $PIDFILE; exiting"
        exit 1
    fi
}

function clean-up() {
    rm "$PIDFILE"
}

cd /scratch

if [[ -f "$PIDFILE" ]]; then
    # If the lock file exists... (the script is either running another
    # instance or improperly exited earlier)
    read PID_SAVED < "$PIDFILE" # Get the PID of the running cleanup script

    if ps --pid "$PID_SAVED" &> /dev/null; then
        # If a PID with this process exists...
        echo "Cleanup script is already running with PID $PID_SAVED; exiting"
        exit 1
    else
        save-pid "$PID_NOW"
    fi
else
    save-pid "$PID_NOW"
fi

trap clean-up HUP INT QUIT ILL ABRT BUS SEGV PIPE TERM ERR
# If any further command raises a problematic signal or exits in error,
# clean up $PIDFILE on the way out

ls | xargs -P "$NUM_PROCS" -I{} \
    find {} -type f -mtime "+$LIMIT_TIME" -delete

clean-up

I'll consider any advice you have to offer, but I'm specifically curious about how I can improve my file locking and error handling.


texts:
I want to optimize my Apriori algorithm for speed:

from itertools import combinations
import pandas as pd
import numpy as np

trans=pd.read_table('output.txt', header=None,index_col=0)

def apriori(trans, support=0.01, minlen=1):
    ts=pd.get_dummies(trans.unstack().dropna()).groupby(level=1).sum()

    collen, rowlen  =ts.shape

    #-------------Max leng (not used)
    #tssum=ts.sum(axis=1)
    #maxlen=int(tssum.loc[tssum.idxmax()])

    pattern = []
    for cnum in range(minlen, rowlen+1):
        for cols in combinations(ts, cnum):
            patsup = ts[list(cols)].all(axis=1).sum()
            patsup=float(patsup)/collen
            pattern.append([",".join(cols), patsup])
    sdf = pd.DataFrame(pattern, columns=["Pattern", "Support"])
    results=sdf[sdf.Support >= support]

    return results

When you input a dataframe of transactions:

>>> trans
        1  2    3    4
0
11      a  b    c  NaN
666     a  d    e  NaN
10101   b  c    d  NaN
1010    a  b    c    d
414147  b  c  NaN  NaN
10101   a  b    d  NaN
1242    d  e  NaN  NaN
101     a  b    c  NaN
411     c  d    e  NaN
444     a  b    c  NaN

[10 rows x 4 columns]

It will yield:

Ap=apriori(trans)
print Ap
>>>
   Pattern  Support
0        a      0.6
1        b      0.7
2        c      0.7
3        d      0.6
4        e      0.3
5      a,b      0.5
6      a,c      0.4
7      a,d      0.3
8      a,e      0.1
9      b,c      0.6
10     b,d      0.3
12     c,d      0.3
13     c,e      0.1
14     d,e      0.3
15   a,b,c      0.4
16   a,b,d      0.2
18   a,c,d      0.1
20   a,d,e      0.1
21   b,c,d      0.2
24   c,d,e      0.1

I want to know if this can be optimized further so that it can run faster on large datasets.  I also want to know if there a way to use purely Pandas without combinations from itertools.


texts:
I'm working on a Unix machine where I can't use more than vanilla Perl, and I'm using Perl5.8.  This script exits with a 1 if the current directory size is smaller than 1 GB (the character after -d is a literal "tab" character).

my $du = `du --si | tail -1 | cut -d"   " -f1`;
chomp $du;
if (substr($du, -1) ne "G") {
    exit 1;
}
exit 0;

This is gross, but I know the data is in du --si so I can write it in 30 seconds.  Is there a cleaner, more robust way?


texts: I'm reading all lines of another sheet and I paste the value that I want to the active sheet VBA

texts:
I have a program that read thousands of lines and return the value that I need. The problem is that request take a lot of time probably like 1min just to search and paste the value, even when I'm saving the code it takes a lot of time...

I think it is around this line that the code is slow :

If Sheets("MT950").Cells(line, 1) Like "-}{5:*" Then

Here is my code :

Function mysolde62(mycurrency As String, swift As String) As Double

Dim SearchString As String
Dim LastLine As Long, line As Long, k As Long
Dim mybegin As Long, myend As Long, test As Long, count As Long
Dim sign As String
Dim myvalue As Double

LastLine = Sheets("MT950").Range("A1").End(xlDown).Row

count = 0
myend = 1

For line = 1 To LastLine

If Sheets("MT950").Cells(line, 1) Like "-}{5:*" Then

SearchString = Sheets("MT950").Range("A" & line).Value

mypos = InStr(1, SearchString, swift, 1)
If mypos <> 0 Then
    count = count + 1
End If

End If
Next line

For k = 1 To count

For line = myend To LastLine
If Sheets("MT950").Cells(line, 1) Like "-}{5:*" Then
    SearchString = Sheets("MT950").Range("A" & line).Value

    mypos = InStr(1, SearchString, swift, 1)
    If mypos <> 0 Then

        mybegin = line
        For linebis = mybegin To LastLine
            If Sheets("MT950").Cells(linebis, 1) Like ":62F:*" Then
                SearchString = Sheets("MT950").Range("A" & linebis).Value

                mypos = InStr(1, SearchString, mycurrency, 1)
                If mypos <> 0 Then
                    myend = linebis
                    test = 1
                End If
                Exit For
            End If
        Next linebis

        If test = 1 Then Exit For
    End If
End If
Next line
If test = 1 Then Exit For
Next k

sign = Mid(Sheets("MT950").Cells(myend, 1).Value, 5, 1)
myvalue = Mid(Sheets("MT950").Cells(myend, 1).Value, 15)
If sign = "D" Then
mysolde62 = -myvalue
Else
mysolde62 = myvalue
End If

End Function


texts: Understanding htaccess redirect to HTTPS and WWW

texts:
I have some questions about a code I found on stackoverflow. The code does what I want to do. Redirects to HTTPS and WWW when doesn't exist in URL. But, I want now to understand what I'm doing.
So, here is the code I use:
# Redirect non HTTPS to HTTPS #
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

# Force www #
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L,E=HTTPS:1]

The code above works as expected. Why isn't the code in the next format, as it does the same thing ? Is any difference ?

RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

The first line of code looks a little bit ambiguous. So I try to modify with:

RewriteCond %{HTTPS} != on # Put a space before on

Or:
RewriteCond %{HTTPS} != 'on' # Put on in single quotes

Or:
RewriteCond %{HTTPS} != "on" # Put on in double quotes

And it doesn't work. Can you please explain why ?

I found some users which are using:

RewriteCond %{HTTPS} off

and not:
RewriteCond %{HTTPS} !=on

I understand that one line checks if the https is off and another one if https is not on. We can say they do the same thing. There are other differences here ? Can HTTPS not be neither on or off ? If the answer is yes, that means the line RewriteCond %{HTTPS} !=on is better than RewriteCond %{HTTPS} off. Isn't it ?
4 When forcing www I have E=HTTPS:1 flag, which means I set the variable HTTPS with value 1. I don't understand the reason... When and who checks for this variable ?
Here, on question 4 I try to rename HTTPS to HTTPSaaa and then, with php, to get all server variable (from $_SERVER). I don't find HTTPSaaa. So this means that the flag is used only by htaccess ? So, I ask again. What's the reason for this flag/variable to exist ?
PS: If someone want's to answer, please specify the question number. I am already a little bit confused...


texts:
I need your opinion about my practice. I want to improve it.

The requirements are the following:

RESTFUL + OWIN (SelfHosted)
Endpoint - Upload a file asynchronously
Make a request to the endpoint from Postman

Well, This is what I got

For the OWIN selfhosted I followed the Microsoft Documentation

OWIN Self-host

Endpoint:

FileController.cs

    [HttpPost]
    [Route("api/v1/upload")]
    public HttpResponseMessage Post([FromUri]string filename)
    {
        var task = this.Request.Content.ReadAsStreamAsync();
        task.Wait();
        Stream requestStream = task.Result;

        try
        {
            Stream fileStream = File.Create("./" + filename);
            requestStream.CopyTo(fileStream);
            fileStream.Close();
            requestStream.Close();
        }
        catch (IOException)
        {
            throw new HttpResponseException( HttpStatusCode.InternalServerError);
        }

        HttpResponseMessage response = new HttpResponseMessage();
        response.StatusCode = HttpStatusCode.Created;
        return response;
    }

Postman:

The postman returns Status Code 201


texts: Combining horizontal and vertical sliders into one

texts:
I'm combining 2 UISliders made from scratch -- one horizontal and one vertical -- to make a single slider that controls 2 parameters. They are set up so that the  vertical slider is perpendicular to the horizontal one. (Like a cross) The thumb knob can move both horizontally and vertically, and if it's moved horizontally, the vertical tracker will move left and right to follow the thumb.

I'm having trouble setting the boundaries of the thumb. Its leftmost limit is supposed to be reached when the left edge of the v. slider touches the left edge of the horizontal slider, and the rightmost limit is when the right edges of the sliders intersect. For the sake of consistency, I took whatever code I needed to obtain the previous conditions and used a similar structure for the top and bottom limits -- even though there is no actual intersection.

This is what I came up with. (This is in a custom UIView which holds both sliders. Also, the size of the UIView is 100 x 100, and the sliders are each 90 points long.)

- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {

CGPoint touchPoint = [touch locationInView:self];

CGFloat hLimitLeft = horizontalSliderFrame.origin.x + .5* ksliderThickness;
CGFloat hLimitRight = horizontalSliderFrame.origin.x + horizontalSliderFrame.size.width - .5* ksliderThickness;
CGFloat vLimitTop = verticalSliderFrame.origin.y + .5* ksliderThickness;
CGFloat vLimitBottom = verticalSliderFrame.origin.y +  verticalSliderFrame.size.height - .5* ksliderThickness;

CGRect thumbBoundaries = CGRectMake(hLimitLeft, vLimitTop, hLimitRight - hLimitLeft, vLimitBottom - vLimitTop) ;

if (CGRectContainsPoint(thumbBoundaries, touchPoint)) {

    self.thumb.center = CGPointMake(touchPoint.x, touchPoint.y);

    [self setNeedsDisplay];
    [self updateValues];

}

return YES;

}

Generally, it works fine. However, it doesn't move at the edges because the touch usually lies outside the boundaries even when it's holding on to the thumb knob.

I'm wondering if there's a better way to design this code.


texts: Module to validate and sum a string containing no negative numbers

texts:
To learn the language of JavaScript, I did a dojo exercise by Roy Osherove. Is there a better way to organize this so that the only method exported is add while keeping it in one single module?

module.exports = {
  add: function (string) {
    this._checkForError(string);
    this._checkForNegatives(string);
    return this._result(string);
  },

  _result: function (string) {
    var numbers = this._numbers(string);
    var result = numbers.reduce(function (sum, number) {
      return sum + number;
    });
    return result;
  },

  _numbers: function (string) {
    var modded = this._modded(string);
    var numbers = modded.map(function (number) {
      return parseInt(number, 10) || 0;
    });
    return numbers;
  },

  _checkForError: function (string) {
    if (string.match(/\n$/)) {
      throw 'Expression ending in newline!';
    }
  },

  _negatives: function (string) {
    var numbers = this._numbers (string);
    var negatives = numbers.filter(function (number) {
      return number < 0;
    });
    return negatives;
  },

  _delimiter: function (string) {
    return (string.substr(0, 2) === '//') ? string[2] : ',';
  },

  _checkForNegatives: function (string) {
    var negatives = this._negatives(string);
    if (negatives.length > 0) {
      throw 'Negatives not allowed: ' + negatives.join(', ');
    }
  },

  _modded: function (string) {
    var delimiter = this._delimiter(string);
    return string.replace(/\n/, delimiter)
      .split(delimiter);
  }
};


texts: Modularized program to find circumference, diameter, and area from a circle's radius

texts:
I have to create a modularized program that can find out the diameter, circumference, and area of a circle's radius. I'm sure many of you can notice I kind of winged this from a example given from my teacher. Instead of people pointing out the fact that I coded this wrong, could you please give me reasons for what I should do so I can better understand this concept?

import math

def main():
    Radius = 0
    Diameter = 0
    Circumference = 0
    Area = 0

    Radius = GetRadius(Radius)
    Diameter = SetDiameter(Radius, Diameter)
    Circumference = SetCircumference(Radius, Circumference)
    Area = SetArea(Radius, Area)
    ShowResults(Radius, Diameter, Circumference, Area)

def GetRadius(myradius):
    myradius = float(str(input("Enter your radius: ")))
    return myradius

def SetDiameter(myradius, mydiameter):
    mydiameter = myradius * 2
    return mydiameter

def SetCircumference(myradius, mycircumference):
    PIE = 3.14159
    mycircumference = 2 * PIE * myradius
    return mycircumference

def SetArea(myradius, myarea):
    PIE = 3.14159
    myarea = PIE * myradius * myradius
    return myarea

def ShowResults(Radius, Diameter, Circumference, Area):
    print("The Diameter is",mydiameter)
    print("The Circumference is",mycircumference)
    print("The Area is",myarea)

main()


texts: Print words in decreasing order of frequency in Scala

texts:
Given a string print its words in decreasing order of frequency.

  Example:

i/p - "aa bbb  ccc aa ddd aa ccc"
o/p - aa,ccc,ddd,bbb

Scala:

import collection.mutable.PriorityQueue
import collection.mutable.HashMap

object FindWordFreq extends App {
  case class wordFreq(w: String, c: Int) extends Ordered[wordFreq] {
    override def compare(that: wordFreq): Int = c compareTo(that.c)
  }
  val words = "aa bbb  ccc aa ddd aa ccc" split " +"
  val wordCount = HashMap[String, Int]()
  for  (word <- words)  {
    wordCount += (word -> (wordCount.getOrElse(word,0) + 1))
  }
  val myHeap = PriorityQueue[wordFreq]()
  wordCount.toSeq foreach { case (w,c) => myHeap.enqueue(wordFreq(w,c))  }
  println(myHeap.dequeueAll.map(_.w).mkString(","))
}

I do think that we can just do with Priority Queue (and get rid of map), but could not come up with very clean code with that.


texts: Improving sqlite3 code in swift using c api

texts:
Trying to come up with a pattern where the code to open db, writing queries is elegant and clean while handling all possible error conditions.
Following code
let file = try! FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("mydb.db")

var result = sqlite3_open(file.path, &database)

if result == SQLITE_OK {
    defer { sqlite3_close(database) }
} else {
    print("couldn't open database")
    return
}

result = sqlite3_exec(database, "CREATE TABLE IF NOT EXISTS department(id INTEGER PRIMARY KEY, name TEXT NOT NULL)", nil, nil, nil)
if result != SQLITE_OK {
    print("couldn't insert into department")
    return
}

result = sqlite3_exec(database, "INSERT OR REPLACE INTO department(id, name) VALUES(0, 'HR'), (1, 'Sales'), (2, 'Accounts'), (3, 'Shipping')", nil, nil, nil)
if result != SQLITE_OK {
    print("error inserting")
    return
}


texts: Counting all the vowels in a passage of text

texts:
My son just started high school and in Math, he was asked to do some stats homework. The exercise was to count all the vowels in a passage of text, then answer some questions about frequency.

Out of curiosity, I wrote a quick Python script to count the vowels:

text = "Australian Rules Football is a ball game played by two teams of eighteen players with an ellipsoid ball on a large oval field with four upright posts at each end. Each team attempts to score points by kicking the ball through the appropriate posts (goals) and prevent their opponents from scoring. The team scoring the most points in a given time is the winner. Usually this period is divided into four quarters of play.Play begins at the beginning of a quarter or after a goal, with a tap contest between two opposing players (rucks) in the centre of the ground after the umpire either throws the ball up or bounces it down."

vowels = {'a':0, 'e':0, 'i':0, 'o':0, 'u':0}

for t in text:
    if t.lower() == 'a':
        vowels['a'] = 1 + vowels['a']
    elif t.lower() == 'e':
        vowels['e'] = 1 + vowels['e']
    elif t.lower() == 'i':
        vowels['i'] = 1 + vowels['i']
    elif t.lower() == 'o':
        vowels['o'] = 1 + vowels['o']
    elif t.lower() == 'u':
        vowels['u'] = 1 + vowels['u']

print vowels

I don't claim to be very good at Python. I enjoy mucking around with it, but I think I'm missing something here. The script works, but I'm clearly repeating myself in the for loop. What's the better "Pythonic" was for me to have done this?


texts: Taking n lines from a file which contains m lines, repeating the file lazily if necessary

texts:
The desire for such a function came out of the necessity of generating a "source" of Lorem ipsum by repeating over and over the same 50 or something paragraphs of the text.
Actually I am curious to know how to do it in C++ (I guess boost::hana has something to offer in this respect), and I have asked a question on StackOverflow about it aleady.
However, to get a better understanding of the functional approach, here's my working solution in Haskell,
import System.IO (readFile)
main :: IO ()
main = (\x -> readFile "file" >>= putStrLn . unlines . take x . concat . repeat . lines)
       =<< return . read
       =<< getLine

where

I'm not sure about the return . read type being the best choice there where it is (one reason being that it doesn't crash gracefully if main is fed with a non-numeric input), and
I haven't written the lambda totally in point-free because I think it would be less readable.
Most importantly, I'm not sure this works lazily in all its parts, but I'd really like to understand this bit.

The program above assumes the current directory contains a text file named file, which can contain something like this,
line1
line2
line3

Given this, one can compile and run obtaining this, for instance:
ghc --make -dynamic program.hs && ./program <<< 7
line1
line2
line3
line1
line2
line3
line1

Any suggestions?


texts: A pythonic way of de-interleaving a list (i.e. data from a generator), into multiple lists

texts:
I've recently discovered the wonders of the Python world, and am quickly learning. Coming from Windows/C#/.NET, I find it refreshing working in Python on Linux. A day you've learned something new is not a day wasted.

I need to unpack data received from a device. Data is received as a string of "bytes", of arbitrary length. Each packet (string) consists of samples, for eight channels. The number of samples varies, but will always be a multiple of the number of channels. The channels are interleaved. To make things a bit more complex, samples can be either 8 or 16 bits in length. Check the code, and you'll see.

I've already got a working implementation. However, as I've just stumbled upon generators, iterators, maps and ... numpy, I suspect there might be a more efficient way of doing it. If not efficient, maybe more "pythonic". I'm curious, and if someone would spend some time giving me a pointer in the right (or any) direction, I would be very grateful. As of now, I am aware of the fact that my Python has a strong smell of C#. But I'm learning ...

This is my working implementation. It is efficient enough, but I suspect it can be improved. Especially the de-interleaving part. On my machine it prints:

time to create generator: 0:00:00.000040
time to de-interleave data: 0:00:00.004111
length of channel A is 750: True

As you can see, creating the generator takes no amount of time. De-interleaving the data is the real issue. Maybe the data generation and de-interleaving can be done simultaneously?

This is not my first implementation, but I never seem to be able to drop below approx 4 ms.

from datetime import datetime

def unpack_data(data):
    l = len(data)
    p = 0

    while p < l:
        # convert 'char' or byte to (signed) int8
        i1 = (((ord(data[p]) + 128) % 256) - 128)
        p += 1
        if i1 & 0x01:
            # read next 'char' as an (unsigned) uint8
            #
            # due to the nature of the protocol,
            # we will always have sufficient data
            # available to avoid reading past the end
            i2 = ord(data[p])
            p += 1
            yield (i1 >> 1 << 8) + i2
        else:
            yield i1 >> 1

# generate some test data ...
test_data = ''
for n in range(500 * 12 * 2 - 1):
    test_data += chr(n % 256)

t0 = datetime.utcnow()

# in this example we have 6000 samples, 8 channels, 750 samples/channel
# data received is interleaved: A1, B1, C1, ..., A2, B2, C2, ... F750, G750, H750
channels = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H')

samples = { channel : [] for channel in channels}

# call unpack_data(), receive a generator
gen = unpack_data(test_data)

t1 = datetime.utcnow()

print 'time to create generator: %s' % (t1-t0)

try:
    while True:
        for channel in channels:
            samples[channel].append(gen.next())
except StopIteration:
    pass

print 'time to de-interleave data: %s' % (datetime.utcnow()-t1)

print 'length of channel A is 750: %s' % (len(samples['A']) == 750)


texts: Flattening multiple nested node readline questions

texts:
Say I'm creating a simple CLI. I want to use native node readline module to take in some input from user at prompt. I thought of this:

var prompt = chalk.bold.magenta;
var info = {};

rl.question(prompt('Thing One : '), function(args) {
    info.one = args;
    rl.question(prompt('Thing Two : '), function(args) {
        info.two = args;
        rl.question(prompt('Thing Three : '), function(args) {
            info.three = parseInt(args);
            rl.close();
            runSomeOtherModuleNow();
        })
    })
});

This does seem to work in a way I'd like, but this seems like a bad approach. I'd much prefer a flatter code than a pyramid like this.


texts: Taking student scores from a file, calculating averages, and printing

texts:
This program takes scores for each student from a .txt file and calculates their averages, as well as the average for each assignment and the class overall. This program works properly, just curious if I can make it look more professional.

Scores.txt

5
6
95.2 89.1 98.0 78.9 100 67
100 99.6 100 100 90.1 82.2
100 85.5 85.1 74 81 79.4
98.6 71.5 68.9 62.4 56.9 0
100 100 100 88.3 91.6 81.3

StudentGradeBookScores.java

import java.util.*;
import java.io.*;
import java.text.*;
public class StudentGradebookScores {
  public static void main(String[]args) throws IOException {

    File inputFile = new File("scores.txt");
    Scanner data = new Scanner(inputFile);
    DecimalFormat averages = new DecimalFormat("#.#");
    int students = data.nextInt();
    int assignments = data.nextInt();
    double gradebook[][] = new double [students + 1][assignments + 1];

    //putting the scores into the array
    for (int i=0; i<students; i++) { //rows
      for (int j=0; j<assignments; j++) { //coloums
        gradebook[i][j] = data.nextDouble();
      }
    }

    //calculating the average assignment score for each student (coloums)
    for (int i=0; i<students; i++) {
      double studentTotal = 0;
      for (int j=0; j<assignments; j++) {
        studentTotal = studentTotal + gradebook[i][j];
      }
      gradebook[i][assignments] = studentTotal/assignments;
    }

    //calculating the average score of each assigment for all students (rows)
    for (int j=0; j<assignments; j++) {
      double assignmentTotal = 0;
      for (int i=0; i<students; i++) {
        assignmentTotal = assignmentTotal + gradebook[i][j];
      }
      gradebook[students][j] = assignmentTotal/students;
    }

    //printing the gradebook
    System.out.print("\t\t\t\tAssignment #:\n\t\t");
    for (int j=0; j<assignments; j++) {
      System.out.print((j+1) + "\t");
    }

    System.out.println("Avg");
    for (int i=0; i<students; i++) {
      System.out.print("Student #" + (i+1) + ":\t");
      for (int j=0; j<assignments; j++) {
        System.out.print(gradebook[i][j] + "\t");
      }
      System.out.println(averages.format(gradebook[i][assignments]));
    }
    System.out.print("Average\t\t");
    for (int j=0; j<assignments; j++) {
      System.out.print(averages.format(gradebook[students][j]) + "\t");
    }
    System.out.println();

    double overallAvg = 0;
    for (int i=0; i<students; i++) {
      overallAvg = overallAvg + gradebook[i][assignments];
    }

    System.out.println("\nOverall Average: " + averages.format(overallAvg/students));
  }
}


texts: AIPlaylist: Adaptive media player using VLCJ and Swing

texts:
I created a project using VLCJ and a probability function to create a media player that plays your favorite media more often than the others, because I wanted to hear my favorite music and videos more than my least favorite. This involved a lot of event listeners that were all at the bottom of my main class file where the components that register the listeners reside. This seemed like a bad way to go about it.

I decided to move each listener to it's own class in the same package and added callback methods in my main class. This worked well, but after several listeners I had to start sifting through to find non-listener classes.

I then decided to put all the listeners in their own package. Now all my listeners and callback methods have to be public.

What is the best way to keep listeners separate from their callback methods? Public callback methods sounds like bad design to me.

I register all the listeners like this,

    // UI listeners
    private final AIPKeyListener keyListener = new AIPKeyListener(this);

This instantiation is with a public AIPListener class in another package.

/**
 *         A custom KeyListener used to listen for key events triggered from an EmbeddedMediaPlayerComponent's VideoSurfaceComponent
 */
public final class AIPKeyListener implements KeyListener {

    // The playlist that contains the methods needed to be called when events are triggered
    AIPlaylist playlist;

    /**       Creates a custom KeyListener used to listen for key events triggered from an EmbeddedMediaPlayerComponent's VideoSurfaceComponent.
     * @param playlist as the playlist that registers this listener with an embeddedMediaPlayerComponent's videoSurfaceComponent.
     */
    public AIPKeyListener(AIPlaylist playlist){
        this.playlist = playlist;
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    /* (non-Javadoc)
     * @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
     */
    @Override
    public void keyReleased(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_COMMA) {
            playlist.bad();
        } else if(e.getKeyCode() == KeyEvent.VK_PERIOD) {
            playlist.good();
        } else if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
            playlist.getLogger().finest("Right");
            playlist.playNext();
        } else if(e.getKeyCode() == KeyEvent.VK_LEFT) {
            playlist.getLogger().finest("Left");
            playlist.playPrevious();
        } else if(e.getKeyCode() == KeyEvent.VK_L) {
            playlist.loopSwitch();
        }
        else if(e.getKeyCode() == KeyEvent.VK_R) {
            playlist.repeatSwitch();
        } else if(e.getKeyCode() == KeyEvent.VK_P) {
            playlist.getLogger().finest("Resetting probabilities");
            playlist.resetProbabilities();
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {

    }

}

The callback methods are in the same class where the listeners are registered.

/** Switches whether looping is enabled or not.
     *
     */
    public void loopSwitch() {
        if(looping) {
            aIPlaylistLogger.finest("Turning loop off");
            mediaListPlayer.controls().setMode(PlaybackMode.DEFAULT);
            if(repeating) {
                mediaListPlayer.controls().setMode(PlaybackMode.REPEAT);
            }
            looping = false;
        } else {
            aIPlaylistLogger.finest("Turning loop on");
            mediaListPlayer.controls().setMode(PlaybackMode.LOOP);
            looping = true;
        }
    }

The full code is here: https://github.com/aljohnston112/AIPlaylist/releases/tag/v0.1.0-0.1.0

My main concern is that having public callback methods callable by anyone is bad practice, but I want to be able to keep the listeners separate from the rest of my project. What is the best way to go about this?


texts: Checking whether a number starts with any of a list of string prefixes

texts:
This code will return false if the long double rand begins with any string in the vector prefix.

bool prefix_vect(long double rand, std::vector<std::string> prefix) {
    std::string str_rand = std::to_string(rand);
    for(auto i : prefix) {
        if(boost::starts_with(str_rand, i))
            return false;
    }
    return true;
}

This code uses #include <boost/algorithm/string/predicate.hpp>.

How can I improve this code? Is there a way to make it fit into one line, such that it could be used without a function at all, and instead in an if-statement?

I am not experienced with C++ lambda expressions, is this something that could use them?

As a note: I don't care if it returns true or false, the Boolean can be switched if it makes this easier to optimize.

Edit: This isn't my main account, just a throwaway (unable to merge accounts, sadly).


texts: Best way to retrieve parameters from associative array in javascript?

texts:
Within a function, I want to grab a set of parameters from a named array. What is the most efficient way of testing if the parameter exists in the array, and if it does, use it as a variable? I came up with a few alternatives.

target = $('#page_links')
if ( functionobject.target ) {
    target = functionobject.target
}

//method 2:
var target = ''
if ( functionobject.target ) {
    target = functionobject.target
}
else {
    target = final_array
}

//method 3:
target = functionobject.target
if (typeof target == 'undefined') {
    target = $('#page_links')
}


texts: Using a loose array just to specify the object properties

texts:
I'm using this array to specify the properties I want to operate on. I didn't use for..in because there's a property that doesn't follow the same pattern.

const data = {};

[
  'teaching_levels',
  'axes',
  'accessibility_resources',
  'contents',
  'resources',
].forEach((name) => {
  data[name] = {
    options: results[name],
    values: req.query[name],
  };
});

// This property is different
data.licenses = results.licenses;

Is it alright to have an array like that?


texts:
I have a navigation, with a sprite that changes based on the class. In my jQuery, I'm clearing out the classes so it will just have .nav and then addClass the right class based on the click.  It works but feels very redundant. Does anyone have suggestions on optimizing this?

HTML:

HOME

GAME STATS

GAME TALK

GAME INFO

JS:

$('DIV.content DIV.nav ul li.home').click(function(){
    $('DIV.content DIV.nav').attr('class', 'nav');
    $('DIV.content DIV.nav').addClass('home');
});

$('DIV.content DIV.nav ul li.game-stats').click(function(){
    $('DIV.content DIV.nav').attr('class', 'nav');
    $('DIV.content DIV.nav').addClass('gamestats');
});

$('DIV.content DIV.nav ul li.game-talk').click(function(){
    $('DIV.content DIV.nav').attr('class', 'nav');
    $('DIV.content DIV.nav').addClass('gametalk');
});
$('DIV.content DIV.nav ul li.game-info').click(function(){
    $('DIV.content DIV.nav').attr('class', 'nav');
    $('DIV.content DIV.nav').addClass('gameinfo');
});


texts: Dropdown menu that opens on click using plain Javascript

texts:
I made a simple dropdown menu which opens when clicked, and closes when the user clicks anywhere outside the menu. The following is the codebase:

function deactivateAllDropdownTriggers() {
   document.querySelectorAll('.dropdown-trigger.active').forEach(function(elem) {
        elem.classList.remove('active');
    })
}

function handleDropdownClicks(event) {
    if (event.target.matches('.dropdown-trigger')) {
        if (event.target.classList.contains('active')) {
            event.target.classList.remove('active');
        } else {
            deactivateAllDropdownTriggers();
            event.target.classList.add('active');
        }
    } else {
        if (!event.target.matches('.dropdown-menu *')) {
            deactivateAllDropdownTriggers();
        }
    }
}

document.addEventListener('click', handleDropdownClicks, false);
.dropdown {
    display: inline-block;
    position: relative;
}
.dropdown .dropdown-menu {
    display: none;
    position: absolute;
    -moz-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
    -webkit-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
    width: auto;
    border: 1px solid rgba(0, 0, 0, 0.15);
    border-radius: var(--border-radius);
    background-color: #ffffff;
    z-index: 1;
}
.dropdown .dropdown-menu ul {
    padding: 0;
    margin: 0;
}
.dropdown .dropdown-menu ul > li {
    list-style: none;
    margin: 0;
}
.dropdown .dropdown-menu ul > li.dropdown-menu-content {
    padding: 0.6rem 1.2rem;
    white-space: nowrap;
}
.dropdown .dropdown-menu ul > li.dropdown-menu-divider {
    height: 1px;
    background-color: rgba(0, 0, 0, 0.05);
}
.dropdown .dropdown-menu ul > li > a {
    display: block;
    text-decoration: none;
    padding: 0.6rem 1.2rem;
    color: rgba(0, 0, 0, 0.8);
    cursor: pointer;
    white-space: nowrap;
    min-width: 12rem;
}
.dropdown .dropdown-menu ul > li > a:hover {
    background-color: rgba(0, 0, 0, 0.025);
}
.dropdown .dropdown-trigger.on-click.active + .dropdown-menu {
    display: block;
}

    <button class="dropdown-trigger on-click">Pick your weapon</button>

                Weapons

Sword

Lance

Axe

Bow

    <button class="dropdown-trigger on-click">Pick your class</button>

                Classes

Fighter

Archer

Thief

Ninja

One thing that concerns me is the open event listener. I could not create a system where an event listener is added to the document when a menu is opened, and the event listener is removed when the menu is closed. Perhaps one of you could help me with that.

Anyway, would appreciate a review of this code.


texts: Largest common subsequence algorithm in C++

texts:
I'm relatively new to C++ and am trying to learn good programming practices and habits from the beginning. The code I wrote finds the largest common subsequence between to strings (and output the resulting subsequence, not the length of the subsequence).

I was wondering if there were any improvements I could make to make this more efficient. I know that it is exponential run-time, and there is a more efficient approach via dynamic programming, but I am simply interested in improving this specific algorithm (i.e. the recursive approach). For instance, I know that maybe concatenating my strings via += may be expensive, or maybe there is a way to use references to avoid the copying of strings.

#include <string>
#include <iostream>

// utility function to return the largest (wrt length) of two strings
std::string& max(std::string &s1, std::string &s2)
{
    return s1.size() > s2.size() ? s1 : s2;
}

// Return the lowest common sequence of characters contained in the
// strings s1 and s2 (as a string)
// e.g. lcs("ACBEA", "ADCA") -> "ACA" (string objects, not const char *)
std::string lcs(std::string s1, std::string s2)
{
    // initialize the lcs to be an empty string
    std::string lcsStr;

    if (s1.empty() || s2.empty())
        return std::string(); // empty string constructor

    if (s1.at(s1.size() - 1) == s2.at(s2.size() - 1))
    {
        lcsStr.push_back(s1.at(s1.size() - 1));
        s1.pop_back();
        s2.pop_back();
        return lcs(s1, s2) += lcsStr;
    }

    else
        return max(
            lcs(s1.substr(0, s1.size() - 1), s2), lcs(s1, s2.substr(0, s2.size() - 1))
        ) += lcsStr;
}

int main()
{
    std::cout << "Enter two strings:" << std::endl;
    std::string s1, s2;
    std::cin >> s1 >> s2;

    std::cout << lcs(s1, s2) << std::endl;

    return 0;
}


texts: Build a MySQL upsert query to insert/update multiple records in Python

texts:
I'm generating a multi-row insert/update with the MySQLdb/MySQL-python module from lists of data rows and field names. For reference, see the executemany() example in the docs.

You can see some revised code on GitHub.

def upsert(db,table,fields,object_list):
    cursor = db.cursor();
    placeholders = ["%s" for x in fields]
    assignments = ["{x} = VALUES({x})".format(x=x) for x in fields]

    query_string = """INSERT INTO
    {table}
    ({fields})
    VALUES
    ({placeholders})
    ON DUPLICATE KEY UPDATE {assignments}"""

    cursor.executemany(query_string.format(
        table = table,
        fields = ", ".join(fields),
        placeholders = ", ".join(placeholders),
        assignments = ", ".join(assignments)
    ),object_list)
    db.commit()

Should I be quoting or escaping some strings/fields? The data is made safe by parameterized queries, but the table and field names could still cause trouble. I'm less concerned about security than failed queries due to odd characters.

Is there already a library out there for this? The existing solutions for upsert and batch-insert seem more generalized, and therefore slower, than implementing a MySQL-specific solution.

Also, I'm clearly in love with str.format()—is this the best way of handling string composition?

Here's some code to run the function, assuming a database named demo exists and mysql is listening on the localhost socket.

import MySQLdb
db = MySQLdb.connect(host="localhost", user="root", passwd="", db="demo", charset="utf8")
c = db.cursor()

c.execute("""DROP TABLE IF EXISTS upsert_demo""")

c.execute("""CREATE TABLE upsert_demo (
  `id` int(11) unsigned NOT NULL,
  `foo` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8""")

c.execute("""INSERT INTO upsert_demo
  (`id`,`foo`)
  VALUES (1, 'baz')""")

demo_fields = ("id","foo")
demo_objects = [(1,"upserted!"),(2,"new record")]

upsert(db,"upsert_demo",demo_fields,demo_objects)


texts:
Given an N x N matrix of positive integers, I need to find the shortest path from the first cell of matrix to the last cell of matrix. I can move exactly x steps from any cell, where x is the value of the cell. The possible movements are right or down, i.e from any cell M[i][j] I can move to locations M[i + M[i][j]][j] or M[i][j +M[i][j]].

For example:

int[][] matrix =
    {
        {1, 2, 1},
        {1, 1, 1},
        {1, 1, 1}
    };

Returning it as a list of strings, the output would be: [(0, 0), (0, 1), (2, 1), (2, 2)]

I have implemented a working solution, but I am wondering if I can improve anything in terms of time complexity?

Here is the code:

class Node {

    // queue node used in BFS
    // (x, y) represents coordinates of a cell in matrix
    int x, y;

    // maintain a parent node for printing final path
    Node parent;

    Node(int x, int y, Node parent) {
        this.x = x;
        this.y = y;
        this.parent = parent;
    }

    @Override
    public String toString() {
        return "(" + x + ", " + y + ')';
    }
}

class Solution {

    LinkedList<String> shortestPathList = new LinkedList<>();

    public List<String> getShortestPath(int[][] matrix) {

        if (matrix == null) {
            return Collections.emptyList();
        }
        Node node = findPath(matrix, 0, 0);
        AddToPath(node);
        return shortestPathList;
    }

    // possible movements
    private static int[] row = {0, 1};
    private static int[] col = {1, 0};

    // The function returns false if is not a valid position
    private static boolean isValid(int x, int y, int matrixLength) {
        return (x >= 0 && x < matrixLength) && (y >= 0 && y < matrixLength);
    }

    // Find shortest route in the matrix from source cell (x, y) to
    // destination cell (N - 1, N - 1)
    public static Node findPath(int matrix[][], int x, int y) {

        int matrixLength = matrix.length;
        // create a queue and enqueue first node
        Queue<Node> q = new ArrayDeque<>();
        Node src = new Node(x, y, null);
        q.add(src);

        // set to check if matrix cell is visited before or not
        Set<String> visited = new HashSet<>();

        String key = src.x + "," + src.y;
        visited.add(key);

        // run till queue is not empty
        while (!q.isEmpty()) {
            // pop front node from queue and process it
            Node curr = q.poll();
            int i = curr.x, j = curr.y;

            // return if destination is found
            if (i == matrixLength - 1 && j == matrixLength - 1) {
                return curr;
            }

            // value of current cell
            int n = matrix[i][j];

            // check both 2 possible movements from current cell
            // and recur for each valid movement
            for (int k = 0; k < 2; k++) {
                // get next position coordinates using value of current cell
                x = i + row[k] * n;
                y = j + col[k] * n;

                // check if it is possible to go to next position
                // from current position
                if (isValid(x, y, matrixLength)) {
                    // construct next cell node
                    Node next = new Node(x, y, curr);

                     key = next.x + "," + next.y;

                     // if it not visited yet
                     if (!visited.contains(key)) {
                         // push it into the queue and mark it as visited
                         q.add(next);
                         visited.add(key);
                     }
                 }
             }
         }

         // return null if path is not possible
         return null;
     }

     //function to get path from start to end
     private void AddToPath(Node node) {
         if (node == null) {
             return;
         }

         shortestPathList.addFirst(node.toString());
         printPath(node.parent);
     }
}


texts: User prompts for entering quiz questions

texts:
I have two methods here  that does the same thing: get the user input and validate them.

If they enter a letter, the program will prompt them again to enter a number. |After that, if it's a number it will compare it to the bound given by the program or the user. It is working fine, but can anybody help me refactor this code? It would be really helpful if I could dissect the validations into smaller pieces of code or methods.

public void addToQuestionToQbank(){
        this.askForCategory();
        System.out.println("Add Questions[1]Multiple Choice[2] Identification: ");
        int choice;
        boolean notValid = true;
        do{
            while(!input.hasNextInt()){
                System.out.println("Numbers Only!");
                System.out.print("Try again: ");
                input.nextLine();
            }
                notValid = false;
                choice = input.nextInt();
        }while(notValid);

        while(choice > 2){
            System.out.println("Out of bounds");
            choice = input.nextInt();
            input.nextLine();
        }
    }

public Difficulty askForDifficulty(){
        System.out.println("Difficulty For This Question:\n1)Easy\n2)Medium\n3)Hard\nChoice: ");
        int choice = 0;

        boolean notValid = true;
        do{
            while(!input.hasNextInt()){
                System.out.println("Numbers Only!");
                System.out.print("Try again: ");
                input.nextLine();
            }
                notValid = false;
                choice = input.nextInt();
        }while(notValid);

        while(choice > diff.length){
            System.out.println("Out of bounds");
            choice = input.nextInt();
            input.nextLine();
        }
        System.out.println(diff[choice -1]);
       return diff[choice -1];
    }


texts: Python solution for the N-Queens challenge

texts:
Here is my coded solution for the N-queens challenge

  The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

The program outputs all valid chess boards, where the queen is represented by the digit 2.

Are there any improvements that can be made to my code?

One of the main things I want to improve is the counter. I have to make the variable global because I can't work out any other way to do it.

"""Find all possible chess-board combinations of size n*n with n queens,
where queens are represented by the digit 2"""
from collections import Counter
import numpy as np

def block_positions(chess_board, row, column, limit):
    """Fills all squares that can no longer contain a queen with the value -1
    There are a maximum of 8 directions that must be blocked from a given square"""
    # Block left
    for col in range(column - 1, -1, -1):
        chess_board[row, col] = 0
    # Block right
    for col in range(column + 1, limit):
        chess_board[row, col] = 0
    # Block up
    for rw in range(row - 1, -1, -1):
        chess_board[rw, column] = 0
    # Block down
    for rw in range(row + 1, limit):
        chess_board[rw, column] = 0
    # Block L up-diag
    rw = row
    col = column
    while rw > 0 and col > 0:
        rw -= 1
        col -= 1
        chess_board[rw, col] = 0
    # Block L down-diag
    rw = row
    col = column
    while rw < limit - 1 and col > 0:
        rw += 1
        col -= 1
        chess_board[rw, col] = 0
    # Block R up-diag
    rw = row
    col = column
    while rw > 0 and col < limit - 1:
        rw -= 1
        col += 1
        chess_board[rw, col] = 0
    # Block R down-diag
    rw = row
    col = column
    while rw < limit - 1 and col < limit - 1:
        rw += 1
        col += 1
        chess_board[rw, col] = 0
    return chess_board

def initialise_board(num):
    """Build the empty board"""
    board = np.ones(num * num).reshape(num, num)
    return board

def valid_boards(board, row, num):
    """Find all valid N-queen boards"""
    global counter
    while row < num:
        indices = [index for index in range(num) if board[row, index] == 1]
        if indices == []:
            return False
        for index in indices:
            old_board = board.copy()
            board[row, index] = 2
            board = block_positions(board, row, index, num)
            is_possible = valid_boards(board, row + 1, num)
            board = old_board
            if not is_possible and index == indices[-1]:
                return False
    flattened = Counter(board.flatten())
    if flattened[2] == num:
        print(board)
        print()
        counter += 1

if __name__ == "__main__":
    counter = 0
    num = 5
    board = initialise_board(num)
    valid_boards(board, row=0, num=num)
    print(counter, "solutions")
    print("Finished")


texts:
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#define STACK_SIZE 100

typedef struct _stack
{
    char *mem;
    size_t size;
    int top;
} STACK;

STACK *stack_create(char *mem, size_t size);
void stack_push(STACK *stack, char c);
char stack_pop(STACK *stack);
char stack_peek(STACK *const stack);
void stack_print(STACK *stack);
int main() {
    char stack_mem[STACK_SIZE];

    STACK *my_stack = stack_create(stack_mem, STACK_SIZE);
    stack_push(my_stack, 'a');
    stack_push(my_stack, 'b');
    stack_push(my_stack, 'c');
    stack_push(my_stack, 'd');
    stack_print(my_stack);
    printf("Top of stack contains: %c\n", stack_peek(my_stack));
    stack_pop(my_stack);
    stack_print(my_stack);
    stack_pop(my_stack);
    stack_pop(my_stack);
    stack_pop(my_stack);
    stack_push(my_stack, 'j');
    stack_push(my_stack, 'k');
    stack_print(my_stack);

    free(my_stack);
    return EXIT_SUCCESS;
}

STACK *stack_create(char *mem, size_t size) {

    assert(mem && size);

    STACK *output = malloc(sizeof(STACK));

    output->mem = mem;
    output->size = size;
    output->top = -1;
    return output;
}

void stack_push(STACK *stack, char c)
{
    assert(stack);

    if(c < 0)
    {
        fprintf(stderr, "This stack is not designed for negative char values\n");
        return;
    }
    if((stack->top + 1) < stack->size)
    {
        stack->mem[stack->top + 1] = c;
        stack->top++;
    }
    return;
}

char stack_pop(STACK *stack)
{
    assert(stack);

    if(stack-> top < 0)
    {
        fprintf(stderr, "Cannot pop from empty stack.\n");
        return -1;
    }

    char o;
    o = stack->mem[stack->top];
    stack->top--;
    return o;
}

char stack_peek(STACK * const stack)
{
    assert(stack);

    if(stack->top < 0)
    {
        fprintf(stderr, "Nothing on stack to peek at.\n");
        return -1;
    }
    return stack->mem[stack->top];
}

void stack_print(STACK *stack)
{
    assert(stack);
    if(!stack->top)
    {
        fprintf(stderr, "Nothing on stack to print.\n");
        return;
    }
    printf("Entire stack:\n");
    int i;
    for(i = stack->top; i >= 0; --i)
    {
        printf("%c\n", stack->mem[i]);
    }
}

Please provide feedback on whatever you see fit, however, error handling would be a helpful focus.


texts: Checking for violation of primary key in a DataTable

texts:
I coded this function to check for a violation of a primary key in a DataTable. The main idea is to retrieve a list of every row that the same value of the column in input and set an error to it.

Private Sub PrimaryKeyCheck(Of ColumnType)(dt As DataTable, ColumnName As String)

    Dim violatingGroups =
        dt.AsEnumerable() _
        .Where(Function(i) i.RowState <> DataRowState.Deleted) _
        .GroupBy(Function(i) i.Field(Of ColumnType)(ColumnName)) _
        .Where(Function(g) g.Count() > 1).ToList()

    For Each violatingGroup In violatingGroups
        For Each violatingRow In violatingGroup
            violatingRow.SetColumnError(ColumnName, "Error, Violating PK") ' TODO Traduzione
        Next
    Next

End Sub

I'm a newbie of Linq, so I'm asking. Is it possible to improve this function in terms of performance and correctness? Is it possible to remove the double for each?


texts:
I have following HTML class collector. Is there a better way than []tap for this?

def tr_classes(user)
  classes = [].tap do |c|
    c << "error" if user.company.nil?
    c << "disabled" if user.disabled?
  end
  if classes.any?
    " class=\"#{classes.join(" ")}\""
  end
end

<tr<%= tr_classes(user) %>>
  <%= user.name %>


texts:
I'm trying to do some task scheduler and worker. Tasks are added to the queue from which worker retrieves and processes them. Tasks from one queue must be executed sequentially. Tasks from different queues are executed in parallel. When the worker has completed all the tasks in the queue, he waits for a while and finishes his work. The queue must be removed from the schedule

I did something, but I think it isn't the best solution. I think there may be problems when worker shuts down and closes the channel.

Is my solution concurrency-safe?

// Schedule struct
type Schedule struct {
    sync.RWMutex
    queues map[int]chan Task
    idle   byte
}

// Scheduler pushes task to the queue
func (s *Schedule) Scheduler(t Task, i int) {
    var queue chan Task
    var ok bool

    s.RLock()
    if queue, ok = s.queues[i]; !ok {
        s.RUnlock()
        s.Lock()
        if queue, ok = s.queues[i]; !ok {
            queue = make(chan Task)
            s.queues[i] = queue
            go s.worker(queue, i)
        }
        s.Unlock()
    } else {
        s.RUnlock()
    }

    queue <- t
}

// Worker retrieves task from the queue and process
func (s *Schedule) worker(c chan Task, i int) {
    timeout := time.After(s.idle * time.Second)
    done := false
    for !done {
        select {
        case task := <-c:
            task.Execute()
            timeout = time.After(s.idle * time.Second)

        case <-timeout:
            s.Lock()
            close(c)
            delete(s.queues, i)
            s.Unlock()
            done = true

        default:
            time.Sleep(10 * time.Millisecond)
        }
    }
}


texts: Better way of checking if the current user already like a post

texts:
I have three models which look like this:

class Post < ActiveRecord::Base
  belongs_to :user, :counter_cache => :count_post
  has_many :likes
end

class User < ActiveRecord::Base
  has_many :posts
  has_many :likes
end

class Like < ActiveRecord::Base
  belongs_to :user
  belongs_to :post, :counter_cache => :count_like
end

A user can only like once per Post so I have a method that checks if the current user already like a post and the dislike link is displayed.

<% if post.has_like_from? current_user %>
    <li id="like_<%= dom_id(post) %>"><%= link_to "like", create_like_path(:post_id => post.id), :remote => true %>

<% else %>
    <li id="dislike_<%= dom_id(post) %>"><%= render 'dislike', :post => post %>

<% end %>

And I have this method on model post:

 def has_like_from?(target_user)
   likes.where(:user_id => target_user.id).first == nil
 end

Is there any way to check every post if current user already like a post? I want to increase performance because load to many posts per request.

Example: startrace when load 7 records

Started GET "/" for 127.0.0.1 at 2014-06-30 23:32:51 +0700
  ←[1m←[35mUser Load (1.0ms)←[0m  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Processing by HomesController#index as HTML
  ←[1m←[36mPost Load (1.0ms)←[0m  ←[1mSELECT "posts".* FROM "posts" ORDER BY created_at DESC←[0m
  ←[1m←[35mLike Load (1.0ms)←[0m  SELECT "likes".* FROM "likes" WHERE "likes"."post_id" = 7 AND "lik
es"."user_id" = 1 LIMIT 1
  ←[1m←[36mLike Load (0.0ms)←[0m  ←[1mSELECT "likes".* FROM "likes" WHERE "likes"."post_id" = 6 AND
"likes"."user_id" = 1 LIMIT 1←[0m
  ←[1m←[35mLike Load (1.0ms)←[0m  SELECT "likes".* FROM "likes" WHERE "likes"."post_id" = 5 AND "lik
es"."user_id" = 1 LIMIT 1
  ←[1m←[36mLike Load (1.0ms)←[0m  ←[1mSELECT "likes".* FROM "likes" WHERE "likes"."post_id" = 4 AND
"likes"."user_id" = 1 LIMIT 1←[0m
  ←[1m←[35mLike Load (0.0ms)←[0m  SELECT "likes".* FROM "likes" WHERE "likes"."post_id" = 3 AND "lik
es"."user_id" = 1 LIMIT 1
  ←[1m←[36mLike Load (0.0ms)←[0m  ←[1mSELECT "likes".* FROM "likes" WHERE "likes"."post_id" = 2 AND
"likes"."user_id" = 1 LIMIT 1←[0m
  ←[1m←[35mLike Load (0.0ms)←[0m  SELECT "likes".* FROM "likes" WHERE "likes"."post_id" = 1 AND "lik
es"."user_id" = 1 LIMIT 1
  Rendered homes/_posts.html.erb (29.0ms)


texts:
I have a photo_shouts_controller.rb and text_shouts_controller.rb which both have almost similar implementations, and I would like to refactor it.

I have implemented a refactoring but I am not too sure if that is the best way to do it.

Current implementation

class PhotoShoutsController < ApplicationController
  def create
    content = build_content
    shout = current_user.shouts.build(content: content)

    if shout.save
      redirect_to dashboard_path
    else
      redirect_to dashboard_path, notice: 'not created!'
    end
  end

  private

  def build_content
    PhotoShout.new(photo_shouts_parameters)
  end

  def photo_shouts_parameters
    params.require(:photo_shout).permit(:image)
  end
end

class TextShoutsController < ApplicationController
  def create
    content = build_content
    shout = current_user.shouts.build(content: content)

    if shout.save
      redirect_to dashboard_path
    else
      redirect_to dashboard_path, notice: 'not created!'
    end
  end

  private

  def build_content
    TextShout.new(text_shouts_parameters)
  end

  def text_shouts_parameters
    params.require(:text_shout).permit(:body)
  end
end

My new implementation

ShoutBuild.rb

class ShoutBuild
  def initialize(current_user, shout_parameters, shout_class)
    @shout_parameters = shout_parameters
    @shout_class = shout_class
    @user = current_user
  end

  def build
    content = build_content
    @user.shouts.build(content: content)
  end

  private

  def build_content
    @shout_class.new(@shout_parameters)
  end
end

Controllers

class TextShoutsController < ApplicationController
  def create
    shout = ShoutBuild.new(current_user, text_shouts_parameters, TextShout).build

    if shout.save
      redirect_to dashboard_path
    else
      redirect_to dashboard_path, notice: 'not created'
    end
  end

  private

  def text_shouts_parameters
    params.require(:text_shout).permit(:body)
  end
end

class PhotoShoutsController < ApplicationController
  def create
    shout = ShoutBuild.new(current_user, photo_shouts_parameters, PhotoShout).build

    if shout.save
      redirect_to dashboard_path
    else
      redirect_to dashboard_path, notice: 'not created!'
    end
  end

  private

  def photo_shouts_parameters
    params.require(:photo_shout).permit(:image)
  end
end


texts: Four-function calculator with roots and powers

texts:
I have some code for a calculator, and I was wondering what I could look at to make the code smaller, easier to read or better in any way. I'm particularly looking at my global variable x. Is there any way to change the code to completely remove that? Someone mentioned a getTwoInputs() function, but with multiple different questions (powers() input and addition() input) I assume it would take up the same space.

def Addition():
    print('Addition: What are your numbers?')
    a = float(input('First Number:'))
    b = float(input('Second Number:'))
    print('Your Answer is:', a + b)

def Subtraction():
    print('Subtraction: What are your numbers?')
    c = float(input('First Number:'))
    d = float(input('Second Number:'))
    print('Your Answer is:', c - d)

def Multiplication():
    print('Multiplication: What are your numbers?')
    e = float(input('First Number:'))
    f = float(input('Second Number:'))
    print('Your Answer is:', e * f)

def Division():
    print('Division: What are your numbers?')
    g = float(input('First Number:'))
    h = float(input('Second Number:'))
    print('Your Answer is:', g / h)

def Roots():
    print('Roots: What do you want to Root?')
    i = float(input('Number:'))
    print('Roots: By what root?')
    j = float(input('Number:'))
    k = ( 1 / j )
    print('Your Answer is:',i**k)

def Powers():
    print('Powers: What number would you like to multiply by itself?')
    l = float(input('Number:'))
    print('Powers: How many times would you like to multiply by itself?')
    m = float(input('Number:'))
    print('Your Answer is:',l**m)

x = 'test'

def Question():
        print('What would you like to do?')
        x = input('(Add, Subtract, Divide, Multiply, Powers, Roots or Quit)')
        if x.lower().startswith('a'):
            x = 'test123'
            print(Addition())
            x = 'test'
        elif x.lower().startswith('d'):
            x = 'test123'
            print(Division())
            x = 'test'
        elif x.lower().startswith('m'):
            x = 'test123'
            print(Multiplication())
            x = 'test'
        elif x.lower().startswith('s'):
            x = 'test123'
            print(Subtraction())
            x = 'test'
        elif x.lower().startswith('r'):
            x = 'test123'
            print(Roots())
            x = 'test'
        elif x.lower().startswith('p'):
            x = 'test123'
            print(Powers())
            x = 'test'
        elif x.lower().startswith('e'):
            x = 'test'
            print(exit())
        elif x.lower().startswith('q'):
            x = 'test'
            print(exit())
        else:
            print("""
Please type the first letter of what you want to do.
""")
            print(Question())

while x == 'test':
    Question()


texts: VBA Data Conversion (random printout -> CSV file)

texts:
I have reviewed the FAQ and I believed it was yes to all 5 q's of "What questions are on-topic for this site?"

Basically, the code below is used to perform the operation shown in the picture. I'm wondering what I can improve in the attached code to clean it up for future reference. Thanks in advance!

Sub Button1_Click()

Dim orgFilename As String
Dim temp As String
Dim strarray(3) As String
Dim vert(4) As String
Dim vert2(3) As String
Dim newFilename As String
Dim numRows As Integer
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim segCount As Integer
Dim vertex(3, 100) As Double

Dim oldwb As Workbook
Dim newwb As Workbook

orgFilename = Application.GetOpenFilename(FileFilter:="All files (*.), *.", Title:="Please select a file")
If orgFilename = "False" Then Exit Sub
Workbooks.OpenText Filename:=orgFilename, _
            Origin:=950, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
            xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=True, Semicolon:=False, _
            Comma:=False, Space:=True, Other:=False, FieldInfo:=Array(Array(1, 1), _
            Array(2, 1), Array(3, 1)), TrailingMinusNumbers:=True
Set oldwb = ActiveWorkbook
Set newwb = Workbooks.Add

oldwb.Activate
Cells(5, 1).Select
numRows = Cells(5, 1).End(xlDown).Row

' Parse through data
segCount = 0
j = 1
For i = 5 To numRows
    If Cells(i, 1) <> "VRTX" And segCount <> 0 Then
        For k = 1 To segCount - 1
            newwb.Worksheets("Sheet1").Cells(j, 1) = "GLINE"
            With newwb.Worksheets("Sheet1")
                .Cells(j, 2) = vertex(1, k)
                .Cells(j, 3) = vertex(3, k)
                .Cells(j, 4) = vertex(2, k)
                .Cells(j, 5) = vertex(1, k + 1)
                .Cells(j, 6) = vertex(3, k + 1)
                .Cells(j, 7) = vertex(2, k + 1)
            End With
            j = j + 1
        Next k
        segCount = 0
    ElseIf Cells(i, 1) = "VRTX" Then
        ' Save vertices to save an endpoint
        vertex(1, segCount + 1) = Cells(i, 3)
        vertex(2, segCount + 1) = Cells(i, 4)
        vertex(3, segCount + 1) = Cells(i, 5)
        segCount = segCount + 1
    End If
Next i

' Save as a new file
temp = Mid$(orgFilename, InStrRev(orgFilename, "\") + 1)
temp = Replace$(temp, ".pl", ".csv")
strarray(1) = Left(orgFilename, InStrRev(orgFilename, "\"))
strarray(2) = "processed_"
strarray(3) = temp
newFilename = Join(strarray, "")
newwb.SaveAs Filename:=newFilename, _
            FileFormat:=xlCSV, _
            Password:="", WriteResPassword:="", ReadOnlyRecommended:=False, _
            CreateBackup:=False
End Sub


texts:
https://leetcode.com/explore/interview/card/top-interview-questions-easy/94/trees/627

  Given a binary tree, check whether it is a mirror of itself (ie,
  symmetric around its center).

  For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

  But the following [1,2,2,null,3,null,3] is not:

   1
   / \
  2   2
   \   \
   3    3

  Note: Bonus points if you could solve it both recursively and
  iteratively.

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

namespace TreeQuestions
{

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */

    /// <summary>
    /// https://leetcode.com/explore/interview/card/top-interview-questions-easy/94/trees/627
    /// </summary>
    [TestClass]
    public class SymmetricTreeTest
    {
        //     1
        //    / \
        //   2   2
        //  / \ / \
        // 3  4 4  3
        [TestMethod]
        public void ValidSymmetricTree()
        {
            TreeNode root = new TreeNode(1);
            root.left = new TreeNode(2);
            root.right = new TreeNode(2);
            root.left.left = new TreeNode(3);
            root.left.right = new TreeNode(4);
            root.right.left = new TreeNode(4);
            root.right.right = new TreeNode(3);
            Assert.IsTrue(SymmetricTree.IsSymmetric(root));
        }

        //    1
        //   / \
        //  2   2
        //   \   \
        //   3    3

        [TestMethod]
        public void NotValidSymmetricTree()
        {
            TreeNode root = new TreeNode(1);
            root.left = new TreeNode(2);
            root.right = new TreeNode(2);
            root.left.right = new TreeNode(3);
            root.right.right = new TreeNode(3);
            Assert.IsFalse(SymmetricTree.IsSymmetric(root));
            Assert.IsFalse(SymmetricTree.IsSymmetricIterative(root));
        }
    }

    public class SymmetricTree
    {
        public static bool IsSymmetric(TreeNode root)
        {
            if (root == null)
            {
                return true;
            }
            return Helper(root.left, root.right);
        }

        public static bool Helper(TreeNode t1, TreeNode t2)
        {

            if (t1 == null && t2 == null)
            {
                return true;
            }

            if (t1 == null || t2 == null)
            {
                return false;
            }

            if (t1.val != t2.val)
            {
                return false;
            }

            //make sure the MIRRORED SIDES are sent!
            return Helper(t1.left, t2.right) && Helper(t1.right, t2.left);
        }

        public static bool IsSymmetricIterative(TreeNode root)
        {
            if (root == null)
            {
                return true;
            }
            Queue<TreeNode> Q = new Queue<TreeNode>();
            Q.Enqueue(root);
            Q.Enqueue(root);
            while (Q.Count > 0)
            {
                TreeNode t1 = Q.Dequeue();
                TreeNode t2 = Q.Dequeue();
                if (t1 == null && t2 == null)
                {
                    continue;
                }
                if (t1 == null || t2 == null)
                {
                    return false;
                }
                if (t1.val != t2.val)
                {
                    return false;
                }
                Q.Enqueue(t1.left);
                Q.Enqueue(t2.right);
                Q.Enqueue(t1.right);
                Q.Enqueue(t2.left);
            }
            return true;
        }
    }
}

Please review for performance