texts:
I wrote my first program in Ruby that compares two CSV files, but I'm sure there are more efficient ways to do it. I tried using the Ruby CSV library at first, but it was unproductive.  Please let me know if you see a better way of doing it. Specifically, I am asking if anyone knows a simpler way to compare two CSV lists other than loading each first and last name into an array and comparing them, then joining them.

Here is a sample name list that I am comparing to:

Kanye,West
Jay,Z
Chance,TheRapper
Two,Chains

# A program to compare two CSV lists
# and return data that is on both lists

# Files must be present in the directory the
# program is in and the two files must
# match the naming conventions in the program

# open an array for each list of names
people = Array.new
people1 = Array.new

# load each list into a variable
first_list = File.open("namelist.csv", "r")
second_list = File.open("namecomplist.csv", "r")

# split the file up by line and push
# the contents of the line to an array
# each element is delineated by the new line
# character "\n"
first_list.each_line { |line|
    fields = line.split('\n')
    people.push(fields)
}

# split the second file up by line and push
# the contents of the line to an array
second_list.each_line { |line|
    fields = line.split('\n')
    people1.push(fields)
}

# There has to be a cleaner way to do the folowing
# Put the data that is in both files in a variable
final_list = people & people1

# convert the array to a string by joing it
final_list1 = final_list.join

# print the matching data and substitute a comma
# for a space for formatting purposes
# the result should be the names of the people
# who are on both lists
puts final_list1.gsub(',', ' ')


texts: Fullscreen slideshow with fading background

texts:
For the past months I have been learning plain javascript without jquery or libraries/frameworks. So now, when I develop a website, I want to write all of the JS code by myself to fully understand what is going on and to learn the language.

So far so good. I tried to implement a slideshow with a fading background image. I had to learn, that although it sounds really simple and straightforward, there are so many things that you have to keep in mind.

For example: how do you stop the slideshow when it is out of view. Otherwise your content below the slideshow might jump up and down because the slides have different heights.

I have realized that I didn't now what I was doing, and that I don't know how to "design" such functionalites. I get "something somehow" to work.

What I am asking for is advice on structuring code for a slideshow like this. Any advice would be gratefully received. Here is a link to the current version of the page. http://jugelt-kk.de/2019/#eins

And some example code:

function topicsSlider(){
  numberTopics();
  dotOnClick();
  iconOnClick();
}

function showNextTopic(){
  // Get index of current active topic
  let currentActive = document.querySelector(".topic.is-active");
  let currentIndex = parseInt(currentActive.dataset.number);
  let nextIndex = currentIndex + 1;

  setHeightOfTopicsContainer(getHeightOfActiveTopic(currentActive) + "px")

  let refreshInterval = setInterval(function(){
    currentActive.classList.remove("is-active");

    topics.forEach( (topic, i) => {
      if(topic.dataset.number == nextIndex){
        // Add active class to icon
        topic.classList.add("is-active");
        setHeightOfTopicsContainer(getHeightOfActiveTopic(topic) + "px")

      } else{
        // Remove active class from icon
        topic.classList.remove("is-active");
      }
    });

    dots.forEach( (dot, i) => {
      if(dot.dataset.number == nextIndex){
        // Add active class to icon
        dot.classList.add("is-active");
      } else{
        // Remove active class from icon
        dot.classList.remove("is-active");
      }
    });

    icons.forEach( (icon, i) => {
      if(icon.dataset.number == nextIndex){
        // Add active class to icon
        icon.classList.add("is-active");
      } else{
        // Remove active class from icon
        icon.classList.remove("is-active");
      }
    });

    setBackgroundImage(nextIndex)

    nextIndex++;

    if(nextIndex > getTopicsCount() ){
      nextIndex = 1;
    }

  }, 3000)

  icons.forEach( icon => {
    icon.addEventListener("click", () => {
      clearInterval(refreshInterval)
    });
  });

}


texts:
I am making a poker application in JavaFX. When I try to display the cards on the screen it is working perfectly fine. Yet I have a method with a lot of duplicated code in it.

I have tried to compress the code into 1 function with a for loop but I couldn't get it to work. Anyone has an idea how to get rid of the duplication?

public class GameController implements Initializable {
    @FXML
    private Canvas canvasBoard;
    @FXML
    private Canvas canvasPlayer1;
    @FXML
    private Canvas canvasPlayer2;
    @FXML
    private Canvas canvasPlayer3;
    @FXML
    private Canvas canvasPlayer4;

    private int playerCardsWidth1 = 0;
    private int playerCardsWidth2 = 0;
    private int playerCardsWidth3 = 0;
    private int playerCardsWidth4 = 0;
    private int dealerCardsWidth = 0;
    private TexasHoldem game;
    private IPlayer board;

    public GameController() {
        try {
            game = new TexasHoldem();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showCardsBoard() {

        board = game.getBoard();

        dealerCardsWidth += 50;
        for (ICard c : board.getCards()) {
            String foto = c.getFilename();
            Image image = new Image(foto);
            GraphicsContext gcBoard = canvasBoard.getGraphicsContext2D();
            int dealerCardsHeight = 0;
            gcBoard.drawImage(image,dealerCardsWidth, dealerCardsHeight,60,80);
            dealerCardsWidth += 75;
        }
    }

    private void showCardsPlayers() {

        List<IPlayer> spelers = game.getPlayers();

        for (int i = 0; i < spelers.size(); i++) {

            if (i == 0) {
                IPlayer player1 = spelers.get(i);
                for (ICard c : player1.getCards()) {
                    Image image = new Image(c.getFilename());
                    GraphicsContext gc1 = canvasPlayer1.getGraphicsContext2D();
                    int playerCardsHeight1 = 0;
                    gc1.drawImage(image, playerCardsWidth1, playerCardsHeight1, 60, 80);
                    playerCardsWidth1 += 75;
                }

            }
            if (i == 1) {
                IPlayer player2 = spelers.get(i);
                for (ICard c : player2.getCards()) {
                    Image image = new Image(c.getFilename());
                    GraphicsContext gc2 = canvasPlayer2.getGraphicsContext2D();
                    int playerCardsHeight2 = 0;
                    gc2.drawImage(image, playerCardsWidth2, playerCardsHeight2, 60, 80);
                    playerCardsWidth2 += 75;
                }
            }
            if (i == 2) {

                IPlayer player3 = spelers.get(i);
                for (ICard c : player3.getCards()) {
                    Image image = new Image(c.getFilename());
                    GraphicsContext gc3 = canvasPlayer3.getGraphicsContext2D();
                    int playerCardsHeight3 = 0;
                    gc3.drawImage(image, playerCardsWidth3, playerCardsHeight3, 60, 80);
                    playerCardsWidth3 += 75;
                }
            }
            if (i == 3) {

                IPlayer player4 = spelers.get(i);
                for (ICard c : player4.getCards()) {
                    Image image = new Image(c.getFilename());
                    GraphicsContext gc4 = canvasPlayer4.getGraphicsContext2D();
                    int playerCardsHeight4 = 0;
                    gc4.drawImage(image, playerCardsWidth4, playerCardsHeight4, 60, 80);
                    playerCardsWidth4 += 75;
                }
            }
        }
    }


texts:
I'm just a beginner in Python. I wrote a simple code that detects the user's password strength, but I feel that it isn't very efficient. How can I improve it?

print('''# This is Password Strength Detector.\n
-----------------------------------------------------------------''')
password = input('Enter your password here : ')
print('\n')

from re import *

lower_match = compile(r'[a-z]').findall(password)  # Finding if the password contains lowecase letters.
upper_match = compile(r'[A-Z]').findall(password)  # Finding if the password contains uppercase letters.
symbol_match = compile(r'[|\"|\'|~|!|@|#|$|%|^|&|*|(|)|_|=|+|\||,|.|/|?|:|;|[|]|{\}|<|>]').findall(
    password)  # Finding if the password contains special characters.
number_match = compile(r'[0-9]').findall(password)  # Finding if the password contains numbers.

if len(password) < 8 or len(lower_match) == 0 or len(upper_match) == 0 or len(symbol_match) == 0 or len(
        number_match) == 0:
    print('Your password is weak ! ')

elif len(password) >= 8:
    print('Your password is strong ! ')

elif len(password) >= 16:
    print('Your password is very strong ! ')


texts:
The staircase has between 1 and 50 flights of stairs, inclusive. Each flight of stairs has between 5 and 30 steps, inclusive. StepsPerStride is between 2 and 5, inclusive. It takes 2 strides to turn around on the landing.

Example:

Input: {15, 15}, StepsPerStride: 2, Returns: 18

There are two flights with a landing in between. 8 strides to get to the first landing, 2 strides to turn around, and 8 more strides to get to the top makes 8+2+8=18 strides

 public class RunUpTheStairs : IRunUpTheStairs
    {
        public ushort CalculateTotalStrides(byte[] stairs, byte stride)
        {
            if (!this.Validate(stairs, stride))
            {
                throw new ArgumentOutOfRangeException("stairs and / or stride are out of range.");
            }

            byte numberOfStrides = 0;
            foreach (byte flight in stairs)
            {
                numberOfStrides += (byte)(flight / stride);

                if (flight % stride != 0)
                {
                    numberOfStrides++;
                }
            }

            ushort totalStrides = (ushort)(numberOfStrides + (stairs.Length - 1) * 2);
            return totalStrides;
        }

        private bool Validate(byte[] stairs, byte stride)
        {
            if (stairs.Length < 1 || stairs.Length > 50)
            {
                return false;
            }

            if (stairs.Any(nextFlight => nextFlight < 5 || nextFlight > 30))
            {
                return false;
            }

            return stride >= 2 && stride <= 5;
        }
    }

I am posting this for code review. Any improvements for performance will be much appreciated too!


texts: Find all files in directory and subdirectories while ignoring noncritical exceptions

texts:
I need to get a list of all files supported by some libary (images) in a specified directory and all subderictories.
Root directory of drive might be chosen and in this case I want to skip system folders like "Windows" and "AppData" (some other?).

For such task I can use Directory.GetFiles() but problem is - it will stop after getting any exception. In this case I need to just ignore noncritical exceptions and skip folders that cause this exception.

This code looks reasonable to me. But I want to make sure that it is done right.

Please tell me if it should be changed somehow.

public static List<string> FindSupportedFiles(string root)
{
    // class from library
    var optimizer = new ImageOptimizer();

    Queue<string> folders = new Queue<string>();
    List<string> files = new List<string>();

    folders.Enqueue(root);
    while (folders.Count != 0)
    {
        string currentFolder = folders.Dequeue();

        if (currentFolder.Contains(":\\Windows") ||
             (currentFolder.Contains(":\\Users") && currentFolder.Contains("\\AppData")))
        {
            if (folders.Count != 0) currentFolder = folders.Dequeue();
            continue;
        }

        string[] filesInCurrent = null;
        try
        {
            filesInCurrent = Directory.GetFiles(currentFolder, "*.*");
        }
        // Ignore this exceptions
        catch (UnauthorizedAccessException) { }
        catch (PathTooLongException) { }
        catch (DirectoryNotFoundException) { }

        foreach (string f in filesInCurrent)
            if (optimizer.IsSupported(f)) files.Add(f);

        string[] foldersInCurrent = null;
        try
        {
            foldersInCurrent = Directory.GetDirectories(currentFolder);
        }
        // Ignore this exceptions
        catch (UnauthorizedAccessException) { }
        catch (PathTooLongException) { }
        catch (DirectoryNotFoundException) { }

        foreach (string _current in foldersInCurrent)
            folders.Enqueue(_current);
    }
    return files;
}


texts: Getting data from API every x seconds and store it in a database

texts:
I'm currently getting data from an API every 15 seconds. This data contains a json with 100-2000 new items every time. Now i don't need all the items that are in there but still quite some of them and i want to store these items in a database. I will probably delete items that are added longer then 5-7 days.

Now i just want to check if the way i'm doing this now is "normal". Because i will run this all day and it's going to get a lot of items.

The script looks like this now:

function fetchItems() {
  axios
    .get("http://lorem.com")
    .then((response) => {

      for (let i = 0; i < response.data.stashes.length; i++) {
        if (some statements) { //filter some of the stashes here with some statements
          stashes.push(filterItems(response.data.stashes[i])); //filter items in stashes and push to new array
        }
      }
      //filtering done
      //add all items to database
      for (let i = 0; i < stashes.length; i++) {
        for (let j = 0; j < stashes[i].items.length; j++) {
          let item = { data i want to store };
          let sql = 'INSERT INTO items SET ?';
          let query = db.query(sql, item, (error, result) => {
            if (error) console.log(error);
            console.log('item added');
          });
        }
      }
    })
    .catch((error) => {
      console.log(error);
    });
}

Is this the way this should be done?


texts:
In a sorted array, I am trying to find pairs that sum up to a certain value. I was wondering if anyone could help me improve my code in performance or memory. I believe my code is O(n). If there are other method for finding pairs the sum up to a certain value that is much more efficient, I am open to these methods!

static int[] intArray = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};

public static ArrayList<String> pairSum(int[] j, int sum) {
    int len = j.length;
    int pointer1;
    int pointer2;
    ArrayList<String> storage = new ArrayList<String>();

    for (int i = 0; i < len; i++) {
        pointer1 = j[i];
        for (int k = len - 1; k >= 0; k--) {
            pointer2 = j[k];
            if (pointer1 + pointer2 == sum && pointer1 != pointer2) {
                i++;
                String pair = Integer.toString(pointer1) + " and " + Integer.toString(pointer2) ;
                storage.add(pair);
            }
        }
    }
    return storage;
}

If I ran this code, say pairSum(intArray,16), I would get:

[0 and 16, 2 and 14, 4 and 12, 6 and 10, 9 and 7, 11 and 5, 13 and 3, 15 and 1]

If I remove the i++, the output would be:

[0 and 16, 1 and 15, 2 and 14, 3 and 13, 4 and 12, 5 and 11, 6 and 10, 7 and 9, 9 and 7, 10 and 6, 11 and 5, 12 and 4, 13 and 3, 14 and 2, 15 and 1, 16 and 0]


texts:
I was asked to implement a graph and BFS and DFS.

Please comment. Is it understandable? Is my algorithm correct? Are there any optimizations?

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

namespace ConsoleApplication2
{
    public class Graph
    {
        public List<Node> list;
        public Graph()
        {
            list = new List<Node>();
        }
    }

    public class Node
    {
        public int Index { get; set; }
        public List<Node> neighbors;
        public Node(int index)
        {
            Index = index;
            neighbors = new List<Node>();
        }
        public void AddNeighbor(int index)
        {
            neighbors.Add(new Node(index));
        }
    }
}

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

namespace ConsoleApplication2
{
    public class BFS
    {
        public BFS()
        {
              Graph graph = new Graph();
              graph.list.Add(new Node(0));
              graph.list.ElementAt<Node>(0).AddNeighbor(1);
              graph.list.ElementAt<Node>(0).AddNeighbor(2);
              graph.list.ElementAt<Node>(0).neighbors.ElementAt<Node>(0).AddNeighbor(3);
              GraphTraverseBFS(graph);
        }
        public void GraphTraverseBFS(Graph graph)
        {
            Queue<Node> queue = new Queue<Node>();
            queue.Enqueue(graph.list[0]);
            while(queue.Count > 0)
            {
                Node tempNode = queue.Dequeue();
                Console.WriteLine("Node number: " +tempNode.Index);
                foreach (var item in tempNode.neighbors)
                {
                    queue.Enqueue(item);
                }
            }
        }
    }
}

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

namespace ConsoleApplication2
{
    public class DFS
    {

        public Graph graph { get; set; }
        public DFS()
        {
              graph = new Graph();

              graph.list.Add(new Node(0));
              graph.list.ElementAt<Node>(0).AddNeighbor(1);
              graph.list.ElementAt<Node>(0).AddNeighbor(2);
              graph.list.ElementAt<Node>(0).neighbors.ElementAt<Node>(0).AddNeighbor(3);
              GraphTraverseDFS(graph);
        }

        public void GraphTraverseDFS(Graph graph)
        {
            Stack<Node> stack = new Stack<Node>();
            stack.Push(graph.list[0]);
            while (stack.Count != 0)
            {
                Node tempNode = stack.Pop();
                Console.WriteLine("Node number: " + tempNode.Index);
                var negibours = tempNode.neighbors;
                foreach (var item in negibours)
                {
                    stack.Push(item);
                }
            }
        }
    }
}


texts: Strip all comments and create a new file with only (JS) code

texts:
This code hasn't been tested exhaustively - I would love suggestions about a testing library.
Critical, Optional and Positive feedback are more then welcome.
const fs = require('fs');

/**
 * strip all comments and create a new file with only code
 * @param {int} file name to clean..
 * @return {int} function returns 0 at the end.
 */
function clean(file) {
  const inputFileName = file;

  // create output file name. e.g: test.js -> test_CLEAN.js
  let outputFileName = inputFileName.split('.');
  outputFileName[0] += '_CLEAN';
  outputFileName = outputFileName.join('.');

  // clean output file old data
  fs.writeFile(outputFileName, ``, (err) => {
    if (err) {
      console.log(err);
    }
  });

  // comments regex defentions
  // lines starts with // where // can have spaces before for indentation
  const singleLineComment = /^\s*\/\//;
  // start skipping lines on /* can have spaces before
  const multiLineCommentStart = /^\s*\/\*/;
  // stop skipping lines on */ end the end of the line
  const multiLineCommentEnd = /\*\/$/;
  // mixed lines with code and inline comments
  const singleLineCommentAfterCode = /[;]\s*\/\//;

  // skip lines bool
  let skipLine = false;

  // load input file to memory, split it by lines, filter white space lines, then loop over each line
  fs.readFileSync(inputFileName, 'utf-8')
      .split(/\n/)
      .filter((line) => line != '')
      .forEach((line) => {
        // return in a forEach() callback is equivalent to continue in a conventional for loop.

        if (multiLineCommentStart.test(line)) {
          skipLine = true;
          return;
        }

        if (multiLineCommentEnd.test(line)) {
          skipLine = false;
          return;
        }

        if (singleLineComment.test(line)) {
          return;
        }

        if (singleLineCommentAfterCode.test(line)) {
          line = line.split(' //')[0];
        }

        // append lines to output file
        if (!skipLine) {
          // append additional \n at the end of a blocks (after '};')
          line = line === '};' ? line + '\n' : line;
          fs.appendFileSync(outputFileName, `${line}\n`, (err) => {
            if (err) {
              // append failed
              console.log(err);
            }
          });
        }
      });

  return 0;
}


texts: Given a sorted array in increasing order, create a BST of minimum height

texts:
I know there are a few recursive ways to solve this problem but the code below is what came to mind for me.

void create_bst(node *root, vector<int> arr)
{
    int len = arr.size();
    add_nodes(root,len-1); //Make the tree structure
    inorder_traversal(root,arr);
}

void add_nodes(node *n, int len)
{
queue<node *> bfs;
bfs.push(n);
int i = 1;

    while(!bfs.empty())
    {
    node *temp = bfs.front();
    bfs.pop();

    temp->left = new node(i++);
    len--;
    if(len == 0)
    {
        break;
    }
    bfs.push(temp->left);

    temp->right = new node(i++);
    len--;
    if(len == 0)
    {
        break;
    }
    bfs.push(temp->right);
    }
}

void inorder_traversal(node *n, vector<int> arr)
{
static int i=0;
if(n->left != NULL)
{
    inorder_traversal(n->left,arr);
}
if(n != NULL)
{
    n->data = arr[i];
    i++;
}
if(n->right != NULL)
{
    inorder_traversal(n->right,arr);
}
}

The add nodes function creates the BST and the inorder traversal function inserts the appropriate values at each node. Is the algorithm above an efficient way to solve this problem?


texts: Summing up distinct elements in steps (follow up)

texts:
This is a "follow up" to an answer I gave on this question : Summing up distinct elements in steps
Here are the OP's requirements :

"My current task is to find a score from an array where the highest/lowest scores have been taken away, and if the highest/lowest occur more than once (ONLY if they occur more than once), one of them can be added:
E.g. int[] scores = [4, 8, 6, 4, 8, 5] therefore the final addition will be ∑4,8,6,5=23.
Another condition of the task is that LINQ cannot be used, as well as any of the System.Array methods (you can see by my previously ask questions that has been a bit of a pain for me, since I solved this with LINQ in less than 5 minutes)."

public int CalculateScore(int[] scores)
{
   int lowestValue = int.MaxValue,
   highestValue = int.MinValue,
   ammountOfHighestValue = 1,
   ammountOfLowestValue = 1,
   finalScore = 0;

   foreach (int score in scores)
   {
      finalScore += score;

      if (score < lowestValue)
      {
         lowestValue = score;
         ammountOfLowestValue = 1; //We need to reset the ammount
      }
      else if (score > highestValue)
      {
         highestValue = score;
         ammountOfHighestValue = 1; //We need to reset the ammount
      }
      else if (score == lowestValue)
         ammountOfLowestValue++;
      else if (score == highestValue)
         ammountOfHighestValue++;
   }

   if (ammountOfHighestValue > 1)
      //This way, we keep the highest score once.
      finalScore -= ((ammountOfHighestValue - 1) * highestValue);
   else
      finalScore -= highestValue; //The value is there once, we remove it.

   if (ammountOfLowestValue > 1)
      finalScore -= ((ammountOfLowestValue - 1) * lowestValue); //Same as highest
   else
      finalScore -= lowestValue;

   return finalScore;
}

I'm interested about how can I remove the multiple if/else statements  while keeping a complexity of O(n) and still loop through the array only once.


texts:
I have multiple drop down lists (select & option) that are populated by data from the server. They all have the same options, but I need the use to be able to select every option only once - it can appear as selected only on one list.

This is the HTML of a single list - simple select & options list:

<div class="social-option">
    <select name="hex_theme_options[social-service-1]">
        <option selected="selected" value="0"></option>
        <option value="facebook">facebook</option>
        <option value="twitter">twitter</option>
        <option value="linkedin">linkedin</option>
        <option value="e-mail">e-mail</option>
        <option value="phone">phone</option>
        <option value="instagram">instagram</option>
        <option value="flickr">flickr</option>
        <option value="dribbble">dribbble</option>
        <option value="skype">skype</option>
        <option value="picasa">picasa</option>
        <option value="google-plus">google-plus</option>
        <option value="forrst">forrst</option>
    </select>
</div>

And this is the JS code for managing them the way I described. It works, but it looks pretty ugly to me, and I'd like to improve it's structure. Any suggestions are welcome.

jsFiddle

(function($){
    $(document).ready(function() {

        var siblings = {
            lock: function (newSelected){
                var selectedSiblings = $('.social-option select').find("option[value=" + newSelected.val() + "]");
                selectedSiblings.not(newSelected).attr('disabled', 'disabled');
            },
            unlock: function (oldSelected){
                var selectedSiblings = $('.social-option select').find("option[value=" + oldSelected.val() + "]");
                selectedSiblings.removeAttr('disabled');
            },
            unlockZero: function (){
                $('.social-option select').find("option[value='0']").removeAttr('disabled');
            }
        };

        function checkSiblings(oldSelected, newSelected) {
            if (oldSelected === '0') {
                siblings.lock(newSelected);
            } else if (newSelected === '0') {
                siblings.unlock(oldSelected);
            } else {
                siblings.unlock(oldSelected);
                siblings.lock(newSelected);
            }
        }

        $('.social-option select').each(function() {
            siblings.lock($('option:selected', this));
            siblings.unlockZero();
        });

        $('.social-option select').on('focus', function () {
            var oldSelected = $('option:selected', this);

            $('.social-option select').on('change', function () {
                var newSelected = $('option:selected', this);
                checkSiblings(oldSelected, newSelected);
            });
        });

    });
})(jQuery);


texts: Update Trigger (Comparing Descriptive string), as well as checking for valid updates

texts:
I have an audit table EpisodesHistory. One of the fields that gets copied is eDescription. I expect eDescription to be regularly be a couple kilobytes in length.

For database space and transmission to client applications, I wanted to do something where if, upon recording the change, eDescription is identical to a previous iteration, it records that value.

Let's say I have this EpisodesHistory table:

HistoryID(PK) | EpisodeID | eDescription | ... other fields
1               10          Watch my dog do a trick
2               10          Watch my cat sleep
3               11          Watch my dog do a trick

In the case of row 3, it was inserted because the episodeID is different.

However, if I then added:

HistoryID(PK) | EpisodeID | eDescription | ... other fields`
4               10          Watch my dog do a trick

I wanted to auto-update an additional field EpisodesHistory.eDescRef to the ID of the row containing the same description. 1 in this case because 1 is the first row to have this field.

It took me a few attempts to get something working so I want to make sure that this is the optimum method as this will be one of the busier triggers in my database.

USE [Shows]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[tr-EpisodesHistory]
on [dbo].[Episodes]
FOR UPDATE
AS

IF TRIGGER_NESTLEVEL(OBJECT_ID('dbo.EpisodesHistory')) > 1
    BEGIN
        RETURN;
    END;

DECLARE @CMP INTEGER
DECLARE @NEWID INTEGER = 0

IF NOT UPDATE(eActor) OR NOT EXISTS((SELECT *, eActor = 0 FROM Inserted except SELECT *, eActor = 0 FROM Deleted))
BEGIN
    -- Weed out updates to episode scoring, or where nothing that matters in the row was changed (eActor doesn't matter)
    -- eVersion is incremented code-side, so this has to be undone.
    -- Could be incremented here instead, but thats yet another query for successful updates
    UPDATE Episodes
      SET eVersion = eVersion - 1
    WHERE EpisodeID = (SELECT EpisodeID From Inserted)
    return;
END

SET @CMP = (Select Top 1 Past.HISTORYID
         FROM DELETED Curr, EpisodesHistory Past
         where Curr.EpisodeID = Past.EpisodeID
           and Curr.eOwner = Past.eOwner
           and Curr.eDescription = Past.eDescription)

SET @CMP = ISNULL(@CMP, 0)
INSERT into EpisodesHistory
SELECT *, eDescRef = @CMP, hWhen = getDate() from deleted;
SET @NEWID = SCOPE_IDENTITY()

IF @CMP > 0
BEGIN
    UPDATE EpisodesHistory
    SET eDescRef = @CMP,
        eDescription = ''
    WHERE HistoryID = @NEWID
END


texts: Take a specified weekday, and check if it falls on the remaining days of the current month

texts:
So like the title says, if we are close to the end of the month, we can check if a given weekday (or array of weekdays) will fall from the current day, to the end of the month. If any of the given days appear, return true, else return false.

I'm quite inexperienced with JS, and this is my first time using the map function. I think splitting the two functions is ok, although I've seen map used with a nested anonymous function.

Any feedback on the solution or the use of map would be appreciated.

// Remember, in the JS date object, months are zero based, days are one based XD
// take a project weekday, and check if it falls on the remaining days of the current month
function check_days_remaining(day) {

  var d = new Date();
  var days_in_month = new Date(d.getYear(), (d.getMonth() + 1), 0).getDate();
  var month_day = d.getDate();
  var month_days_remaining = days_in_month - month_day;

  for(i = 1; i <= month_days_remaining; i++) {
    var index_date = new Date(d.getYear(), (d.getMonth() + 1), (d.getDate()+i) );
    var index_day = index_date.getDay();
    if(index_day == day) {
      //console.log("Weekday: " + index_day + " falls on " + index_date);
      return true;
    }
  }

}

function days_remaining(days) {
  remaining = days.map(check_days_remaining);
  // console.log(remaining); // logs an array of true or undefined elements
  return ( remaining.indexOf( true ) > -1 ) ? true : false; // true if at least one project day is remaining in current month
}

var stay_on_month = days_remaining([5,6]); // set whether to stay on current month or display next month
console.log(stay_on_month); // check result


texts:
Before I tried to avoid using cursor because of performance issues. But now I have to do some calculations to reach some goals. I have a stored procedure that has a code like this:

DECLARE  Outer_Cursor CURSOR FOR...

   OPEN Outer_Cursor
   FETCH NEXT FROM Outer_Cursor INTO ...

   WHILE @@FETCH_STATUS = 0
   BEGIN

      DECLARE  Inner_Cursor CURSOR  FOR...

      OPEN Inner_Cursor
      FETCH NEXT FROM Inner_Cursor INTO ...

      WHILE @@FETCH_STATUS = 0
      BEGIN

        ...

        FETCH NEXT FROM Inner_Cursor INTO ...
      END

      CLOSE Inner_Cursor
      DEALLOCATE Inner_Cursor

      FETCH NEXT FROM Outer_Cursor INTO ...

  END

  CLOSE Outer_Cursor
  DEALLOCATE Outer_Cursor

Is it possible to avoid (minimize) so expensive cursor recreation for inner cursor. How can I reuse inner cursor declaration, if it is possible?


texts: Push Entity Framework exceptions to business layer

texts:
I am trying to write an exception handler/parser, which I want to return from DAL to the business layer. I am writing below class because I don't want my business layer to know if I am using EF under my DAL.

Please suggest if below code adhere to SOLID principles?

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;

namespace WebAPis
{
    public enum ExceptionType
    {
        Unknown,
        EntityModified,
        EntityValidation,
        EntityUpdateException

    }
    public class EfResponse
    {
        private Exception Exception { get; set; }
        public void ParseException(Exception ex)
        {
            this.Exception = ex;
        }
        public bool IsSuccess { get { return this.Exception == null; } }
        public int RowsModified { get; set; }
        public ExceptionType Type
        {
            get
            {
                var type = ExceptionType.Unknown;

                if (this.Exception is DbEntityValidationException)
                    return ExceptionType.EntityValidation;

                if (this.Exception is DbUpdateException)
                    return ExceptionType.EntityUpdateException;

                if (this.Exception is DbUpdateConcurrencyException)
                    return ExceptionType.EntityModified;
                // add more types here
                return type;
            }
        }

        public DbUpdateExceptionDetail GetDbUpdateExceptionDetail
        {
            get
            {
                if (this.Type != ExceptionType.EntityUpdateException)
                    throw new Exception("Invaid exception details invoked");

                var toReturn = new DbUpdateExceptionDetail()
                {
                    // Parse exception here
                    ColumnName = "test column name"
                };
                return toReturn;

            }
        }
        public ConcurrencyExceptionDetail GetConcurrencyExceptionDetail
        {
            get
            {
                if (this.Type != ExceptionType.EntityModified)
                    throw new Exception("Invaid exception details invoked");

                var toReturn = new ConcurrencyExceptionDetail()
                {
                    // Parse exception here
                    MyProperty = "test property name"
                };
                return toReturn;
            }
        }
    }

    // Exception models
    public abstract class ExceptionDetail
    {
        public List<string> Exceptions { get; set; }
    }
    public class DbUpdateExceptionDetail : ExceptionDetail
    {
        public string ColumnName { get; set; }
    }

    public class ConcurrencyExceptionDetail : ExceptionDetail
    {
        public string MyProperty { get; set; }
    }

    // example dbcontext
    public class MyDbcontext : DbContext
    {
        public EfResponse Save()
        {
            var toReturn = new EfResponse();
            try
            {
                toReturn.RowsModified = this.SaveChanges();
            }
            catch (Exception ex)
            {
                toReturn.ParseException(ex);
            }

            return toReturn;
        }
    }
}


texts: Reading a properties file using design patterns

texts:
I am trying to read properties file using a singleton class. I would like to know if there are any best practices and design patterns to read the properties file. I found dependency injection is one way to read properties file. But, I did not find any examples on the DI design pattern. Any sample code and links would be helpful.

package com.cisco.propertiesreader;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Set;

import org.apache.log4j.Logger;

public class ReadProperties {

    private static final Logger LOGGER = Logger.getLogger(ReadProperties.class);

    private final Properties props = new Properties();

    private ReadProperties() {
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("config.properties");
        try {
            props.load(in);
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
    }

    private static class PropHolder {
        private static final ReadProperties INSTANCE = new ReadProperties();
    }

    public static ReadProperties getInstance() {
        return PropHolder.INSTANCE;
    }

    public String getProperty(String key) {
        return props.getProperty(key);
    }

    public Set<String> getAllPropertyNames() {
        return props.stringPropertyNames();
    }

    public boolean containsKey(String key) {
        return props.containsKey(key);
    }
}


texts:
I am currently using:

class RepeatedTimer(object):
    def __init__(self, interval, function, *args, **kwargs):
        self._timer = None
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.is_running = False
        self.start()

    def _run(self):
        self.is_running = False
        self.start()
        self.function(*self.args, **self.kwargs)

    def start(self):
        if not self.is_running:
            self._timer = Timer(self.interval, self._run)
            self._timer.start()
            self.is_running = True

    def stop(self):
        self._timer.cancel()
        self.is_running = False

to run a section of code every 24 hours, however, this looks messy and I think it can be simplified.

I want to run a function every 24 hours.  Is there a simpler and cleaner method?


texts: How optimize set of nested 'if' in one function?

texts:
I have such part of function:

$token = $this->getToken($user);

    if ('main' !== session('type') && is_null($token)) {
        $instagramProfile = $this->findInstagramProfile($user);
        $token = $instagramProfile->profile->user->api_token ?? null;
    } else {
        if (!$instagramProfile = $this->findInstagramProfile($user)) {
            $profile = create_instagram_profile($user);
            $user = $this->createUser($profile);
            $token = $user->api_token;
        } else {
            if($instagramProfile->profile->user) {
                $token = $instagramProfile->profile->user->api_token;
            } else {
                $user = $this->createUser($instagramProfile->profile);
                $token = $user->api_token;
            }
        };
    }

I have many scenarios:

param type which save in session;
instagram profile exist;
user exists.

In worlds - very simple, but in code it stay not understandable.

How I can optimize such part of code?

Maybe create more abstract function?


texts: Remove nodejs/browser specific code in library

texts:
I'm the maintainer of the following library on github: https://github.com/edi9999/docxtemplater/blob/master/coffee/docxgen.coffee

I want to maintain a library that works on node and in the browser, however I don't want to have to update two separate repositories.

The ugliest code looks like this:

root= global ? window
env= if global? then 'node' else 'browser'

if env=='node'
    global.http= require('http')
    global.https= require('https')
    global.fs= require('fs')
    global.vm = require('vm')
    global.DOMParser = require('xmldom').DOMParser
    global.XMLSerializer= require('xmldom').XMLSerializer
    global.PNG= require('../vendor/pngjs/png-node')
    global.url= require('url')

    ["grid.js","version.js","detector.js","formatinf.js","errorlevel.js","bitmat.js","datablock.js","bmparser.js","datamask.js","rsdecoder.js","gf256poly.js","gf256.js","decoder.js","qrcode.js","findpat.js","alignpat.js","databr.js"].forEach (file) ->
        vm.runInThisContext(global.fs.readFileSync(__dirname + '/../vendor/jsqrcode/' + file), file)
    ['jszip.js'].forEach (file) ->
        vm.runInThisContext(global.fs.readFileSync(__dirname + '/../vendor/jszip2.0/dist/' + file), file)

output: (options={}) ->
        if !options.download? then options.download=true
        if !options.name? then options.name="output.docx"
        if !options.type? then options.type="base64"
        result= @zip.generate({type:options.type})
        if options.download
            if env=='node'
                fs.writeFile process.cwd()+'/'+options.name, result, 'base64', (err) ->
                    if err then throw err
            else
                #Be aware that data-uri doesn't work for too big files: More Info http://stackoverflow.com/questions/17082286/getting-max-data-uri-size-in-javascript
                document.location.href= "data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,#{result}"
        result

As you can see, they is a lot of specific node/browser js code, and I would like to remove that from the main code, however, I can't find an easy way to do this.

Any idea ?


texts: VBA code to import data, doing lookups to detect duplicates

texts:
I have an import macro, which creates ID by concatenating cells, then I compare using VLOOKUP with another sheet if any duplicate found.

It's running very slowly, so I want to know better ways to optimize this code, because once finished, I will need to add another "for" for to handle duplicates found and compare dates.

It's one of my first macros in VBA, so I'm sure there are a lot of ways to improve the performance.

Sub ImportData()

Dim wb1 As Workbook
Dim wb2 As Workbook
Dim slr As Long
Dim dlr As Long
Dim Tlr As Long

Set wb1 = ActiveWorkbook

FileToOpen = Application.GetOpenFilename _
(Title:="Select import file", _
FileFilter:="Microsoft Excel Workbooks (*.xls;*.xlsx;*.xlsm),*.xls;*.xlsx;*.xlsm")

If FileToOpen = False Then
    MsgBox "No File Specified.", vbExclamation, "ERROR"
    Exit Sub
Else
    Set wb2 = Workbooks.Open(Filename:=FileToOpen)
    slr = wb2.Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row

    wb2.Worksheets("Sheet1").Range("A8:S" & slr).Copy _
    wb1.Worksheets("INPUT_DATA").Range("A2")
End If

    wb2.Close savechanges:=False

    dlr = wb1.Worksheets("INPUT_DATA").Cells(Rows.Count, 1).End(xlUp).Row
    wb1.Worksheets("INPUT_DATA").Range("A2:S" & dlr).ClearFormats

    For cell = 2 To dlr
        Cells(cell, 20).Formula = "=CONCAT(RC[-19], ""__"",RC[-18])"
    Next

    'check duplicate values before import to TOTAL_DATA
    Tlr = wb1.Worksheets("TOTAL_DATA").Cells(Rows.Count, 1).End(xlUp).Row
    countMatch = 0
    countUnmatch = 0
    For cell = 2 To dlr
        Cells(cell, 21).Formula = "=IF(ISNA(VLOOKUP(RC[-1],TOTAL_DATA!C30,1,FALSE)), ""No"", ""Yes"")"
            If Cells(cell, 21).Value = "Yes" Then
                Cells(cell, 20).Font.Color = vbRed
                countMatch = countMatch + 1
            Else
                Range("A" & cell, "T" & cell).Cut Destination:=wb1.Worksheets("TOTAL_DATA").Range("A" & Tlr + 1)
                Tlr = Tlr + 1
                countUnmatch = countUnmatch + 1
            End If
    Next cell

    If countMatch > 0 Then
            MsgBox "Found duplicates!!" & vbCr & "Number of duplicates : " & countMatch & _
            vbCr & "Duplicate items were keep at INPUT_DATA" & vbCr & _
            "Loaded succesfully : " & countUnmatch & " items", vbExclamation
    Else
            MsgBox "Loaded succesfully : " & countUnmatch & " items"
    End If
End Sub
```


texts: Reading denormalized data using a stateful loop body

texts:
I'm reading denormalized data with a SqlDataReader, the data has this form:

SELECT
    Objects.ObjectName, Objects.OwnerId, Owners.Name
FROM
    Objects
    INNER JOIN Owners ON Objects.OwnerId = Owners.OwnerId
ORDER BY
    Objects.OwnerId

Which has this output:

OjectName      OwnerId    OwnerName
Foo            1          Mr. Fu
Bar            1          Mr. Fu
Baz            2          Mrs. Daz

My reading loop is this:

using( SqlDataReader rdr = cmd.ExecuteReader() )
{
    Int64 lastOwnerId = -1;
    List<String> objectNames = new List<String>();
    while( rdr.Read() )
    {
        String objName   = rdr.GetString( 0 );
        Int64  ownerId   = rdr.GetInt64 ( 1 );
        String ownerName = rdr.GetString( 2 );

        if( ownerId != lastOwnerId && objectNames.Count > 0 )
        {
            // logic to populate and yield-return new Owner w/ ObjectNames

            objectNames.Clear();
            lastOwnerId = ownerId;
        }
        else
        {
            objectNames.Add( objName );
        }
    }

    if( ownerId != lastOwnerId && objectNames.Count > 0 )
    {
        // logic to populate and yield-return new Owner w/ ObjectNames
    }
}

The logic to populate and yield-return new Owner w/ObjectNames  exists twice. Short of moving it to its own function, is there another loop pattern that is DRY?


texts:
How can I refactor this function? I show a list of plugins in JSF, and I should filter them. I added function filterPlugins but I have some questions:

Should we simplify block with conditional expression?
I reassign global variable "plugins" to introduce my filter function (is it not bad practice?)

load()

@NotNull
@DataModel("plugins")
List<Plugin> plugins;

public void load() {
    plugins = pluginManager.getPlugins();

    plugins = filterPlugins(searchParam);

    SortingUtil.sort(plugins, SortingUtil.SortType.ID_ASC);
    if (plugins.size() > 0) {
        if (plugin != null && plugins.contains(plugin)) {
            selectPlugin(plugin);
        } else {
            selectPlugin(plugins.get(0));
        }
    } else {
        plugin = null;
    }
}

@SuppressWarnings("unchecked")
private List<Plugin> filterPlugins(final String searchParam ){
      return (List)Iterables.filter(plugins, new Predicate<Plugin>() {
        @Override
        public boolean apply(@Nullable Plugin plugin) {
            return  plugin.getName().contains(searchParam)
                    || plugin.getNetworkClasses().contains(searchParam)
                    || plugin.getClassName().contains(searchParam);
        }
    });
}

@Override
public void selectPlugin(Plugin p) {
    plugin = p;
}

Plugin.java

public class Plugin {

    private static final long serialVersionUID = -8424575107726996696L;

    @NotNull
    private Long id;

    @NotNull
    private String name;

    @NotNull
    private String networkClasses;

    + setters and getters
}

I want to pay your attention this code interacts with JSF page:

<a:support event="onRowClick" action="#{configPlugins.selectPlugin(p)}" reRender="pluginList"/>
<a:commandLink action="#{configPlugins.removePlugin(true)}" reRender="pluginList"/>


texts: Separate Declaration and Definition of private Node implementation in template Linked List

texts:
I was practicing implementing a template Linked List with a private node implementation.  I know one of the methods to define template class member functions is to keep the declaration and definition in the same header file.  When I tried to do this with the private createNode() function, I could not get it to work.

template<class T>
LinkedList<T>::createNode(const T &data)
{ ... }

I was wondering if there's a way to define the private function createNode() outside of the class declaration?  My current work around is to define this function within the class definition.  As I understand, this is a C++ style no-no though.

Generally speaking, I was wondering if there was anything else I could do with my implementation that could improve readability or make the  code more robust.  I'm open to any and all suggestions!  I suppose the first suggestion is to be consistent with where I place the pointer/reference modifiers...

#include <iostream>

template<class T>
class LinkedList
{
private:
    struct Node
    {
        T data;
        Node* next;
    };

    Node* head;
    Node* tail;
    int size;

    Node* createNode(const T &data)
    {
        Node* newNode = new Node;
        newNode->data = data;
        newNode->next = nullptr;

        return newNode;
    }

public:
    LinkedList();
    void display() const;
    void push(const T &data);
    void insert(const int pos, const T &data);
    void remove(const int pos);

};

template<class T>
LinkedList<T>::LinkedList() : head{ nullptr }, tail{ nullptr }, size{ 0 }
{
}

template<class T>
void LinkedList<T>::display() const
{
    Node* curNode = head;

    while (curNode != nullptr)
    {
        std::cout << curNode->data << std::endl;
        curNode = curNode->next;
    }

    std::cout << std::endl;
}

template<class T>
void LinkedList<T>::push(const T &data)
{
    Node* newNode = createNode(data);

    if (size == 0)
    {
        head = newNode;
        tail = newNode;
    }
    else
    {
        tail->next = newNode;
        tail = newNode;
    }

    ++size;
}

template<class T>
void LinkedList<T>::insert(const int pos, const T &data)
{
    if (pos < 0 || pos > size)
    {
        std::cout << "Index is out of range!" << std::endl;
    }
    else if (pos == size)
    {
        push(data);
    }
    else
    {
        Node* newNode = createNode(data);
        Node* prevNode = head;
        Node* curNode = head;

        int i = 0;
        while (i != pos)
        {
            prevNode = curNode;
            curNode = curNode->next;
            ++i;
        }

        prevNode->next = newNode;
        newNode->next = curNode;

        ++size;
    }
}

template<class T>
void LinkedList<T>::remove(const int pos)
{
    if (pos < 0 || pos > size)
    {
        std::cout << "Index is out of range!" << std::endl;
    }
    else if (size == 0)
    {
        std::cout << "List is empty!" << std::endl;
    }
    else
    {
        Node* prevNode = head;
        Node* curNode = head;

        int i = 1;
        while (i != pos)
        {
            prevNode = curNode;
            curNode = curNode->next;
            ++i;
        }

        prevNode->next = curNode->next;
        delete curNode;

        if (pos == size)
        {
            tail = prevNode;
        }

        --size;
    }
}


texts: wcf service client wrapper for asp.net core

texts:
My goal is to grab some data inside asp.net core app on server from external source via wcf service. In future i would like wcf responses to be cached on server and provide asp.net app clients "normal" errors if they appear.
Some things to notice: I'm using .net core 2.0 and generated wcf service proxy with a help of WCF Connected Service extension. Wcf service is hosted as windows service and exposed via BasicHttpBinding.

First of all, after going through WCF Connected Service wizard, I have IMyWcfService contract and MyWcfServiceClient proxy:

public interface IMyWcfService
{
    Task<GroupWorkout[]> GetGroupScheduleForCurrentWeekAsync();
}

public partial class MyWcfServiceClient : ClientBase<IMyWcfService>, IMyWcfService
{
    ...
    public Task<GroupWorkout[]> GetGroupScheduleForCurrentWeekAsync()
    {
        return base.Channel.GetGroupScheduleForCurrentWeekAsync();
    }
    ...
}

Next, i'm wrapping service calls like this:

public class MyWcfServiceClientHelper : IMyWcfServiceClientHelper
{
    private readonly MyWcfServiceClient _client;

    public MyWcfClientHelper(MyWcfServiceClient client)
    {
        _client = client;
    }

    public async Task<ActionResponse<T>> Call<T>(Expression<Func<IMyWcfService, Task<T>>> expression)
    {
        var result = new ActionResponse<T>();

        try
        {
            result.Result = await expression.Compile()(_client);
        }
        catch (FaultException<MyWcfServiceFault> fault)
        {
            result.Error = new ActionError() { Code = ErrorCodes.WcfExpectedFault, Message = fault.Message };
        }
        catch (CommunicationException ex)
        {
            result.Error = new ActionError() { Code = ErrorCodes.WcfCommunicationError, Message = ex.Message };
            _client.Abort();
        }
        catch (TimeoutException ex)
        {
            result.Error = new ActionError() { Code = ErrorCodes.WcfTimeoutError, Message = ex.Message };
            _client.Abort();
        }
        catch (Exception ex)
        {
            result.Error = new ActionError() { Code = ErrorCodes.UnknownError, Message = ex.Message };
            _client.Abort();

            throw;
        }

        return result;
    }
}

DI regs are:

public static class IServiceCollectionExtensions
{
    public static IServiceCollection AddConnectedServices(this IServiceCollection coll)
    {
        coll.AddScoped<MyWcfServiceClient>();
        coll.AddScoped<IMyWcfServiceClientHelper, MyWcfServiceClientHelper>();

        return coll;
    }
}

And call it like this:

public class ScheduleUnit : IScheduleUnit
{
    private readonly IMyWcfServiceClientHelper _helper;

    public ScheduleUnit(IMyWcfServiceClientHelper helper)
    {
        _helper = helper;
    }

    public async Task<ActionResponse<GroupWorkout[]>> Get()
    {
        //here also will be some logic to resolve where to get data (cache or service call)
        ...
        var data = await _helper.Call(u => u.GetGroupScheduleForCurrentWeekAsync());
        ...
    }
}

ActionResponse, ActionError is my custom classes:

public class ActionResponse<T> : IActionResponse
{
    public T Result { get; set; }

    public bool IsCorrect => Error == null;

    public ActionError Error { get; set; }
}

So, is it ok to recreate service (scoped registration) and not call it if cache is valid? Maybe singleton registration suits more in this case?
Is there any cons of using helper there?
Do Func> parameter for expression is ok? I mean asynchronous call:

await expression.Compile()(_client);

May be you could consider something else to improve with that code?
Thanks in advance.


texts: Iterate through images really fast with JS

texts:
My objective is to modify the JavaScript code to get the single image on the page to iterate through images faster. It should be possible to get the images to load in about 10 seconds(about 3 seconds on Windows). Yet I have 0 clue on how to do this.

<!doctype html>

Image load optimisation test

Time:

Basic I know, but help would be appreciated.

Plnkr below for my working example so far.

https://plnkr.co/edit/N5h7fyFEBMj0C2fC2vgc


texts: Priority Queue Linked List Implementation

texts:
I am new to Python and wanted to make sure my code answers the question for my assignment due.

My Task:

  A priority queue is a queue in which each item is assigned a priority
  and items with a higher priority are removed before those with a lower
  priority, irrespective of when they were added. Integer values are
  used for the priorities with a smaller integer value having a higher
  priority. In an unbounded priority queue, there are no limits on the
  range of integer values that can be used for the priorities.

• PriorityQueue(): Creates a new empty unbounded priority queue.

• isEmpty(): Returns a boolean value indicating whether the queue is empty.

• length(): Returns the number of items currently in the queue.

• enqueue(item, priority): Adds the given item to the queue by inserting it in the proper position based on the given
priority.

• dequeue(): Removes and returns the next item from the queue, which is the item with the highest priority.
If two or more items have the same priority, those items are removed in FIFO order. An item cannot be dequeued from an empty queue.

• peek(): Returns a copy of the next item in the queue, without removing the item. The next item is the same value that would be returned by the dequeue operation. An item cannot be dequeued from an empty queue.

My Code:

class Node( object ) :
    def __init__( self, cargo = None, next = None ) :
        self.cargo = cargo
        self.next = next

 # Creates a new empty unbounded priority queue
class PriorityQueue :

     #
    def __init__( self ) :
        self.length = 0
        self.head = None
        self.last = None

     # Returns a boolean value indicating whether the queue is empty
    def isEmpty( self ) :
        return (self.length == 0)

     # Returns the number of items currently in the queue
    def __len__( self ) :
        return len(self.length)

     # Adds the given item to the queue by inserting it in the proper position
     # based on the given priority. The new node is appeneded to the end of the
     # linked list
    def enqueue( self, item, priority) :
        newNode = Node(cargo)
        newNode.next = None
        if self.length == 0:
            self.head self.last = newNode
        newNode.next = self.head
        self.head = newNode
        self.last.next = newNode
        self.last = newNode

        temp = self.head
        p = self.head.next
        while p != None :
            if p.cargo > newNode.cargo:
                temp = temp.next
                p = p.next
            break
        newNode.next = temp.next
        temp.next = newNode

     # Removes and returns the next item from the queue, which is the item with
     # the highest priority. If two or more items have the same priority, those
     # items are removed in FIFO order. An item cannot be dequeued from an
     # empty queue. The linked list is searched to find the entry with the
     # highest priority.
    def dequeue( self ) :
        cargo = self.head.cargo
        self.head = self.head.next
        self.length = self.length - 1
        if self.length == 0:
            self.last = None
        return cargo


texts: Declaring multiple arrays in PHP with one line

texts:
Is it possible to declare multiple arrays in PHP in one line?

$userAnswers  = array();
$questionIDs = array ();
$sqlAnswers = array();
$sqlAnswersQuery = array();
$correctAnswers = array();

Any cleaner ways of doing this?

NOTE: The contents of these arrays are all DIFFERENT. I don't think setting them equal to each other would work.


texts:
The Go Playground was boring so I decided to make a small application that throws me into the language. It basically queries the chatroom every second for new messages and displays them in the output pane (minus the bots their messages).

It's all new to me so any insight is welcome. One thing I've been particularly unsure about are my return statements and whether I'm using them correctly. Likewise, there are a bazillion different ways to declare a variable; have I done it correctly so far?

package main

import (
    "encoding/json"
    "fmt"
    sanitize "github.com/kennygrant/sanitize"
    "html"
    "io/ioutil"
    "net/http"
    "net/url"
    "strconv"
    "time"
)

type ChatEvent struct {
    Event_type    int8
    Time_stamp    int64
    Content       string
    User_id       int64
    User_name     string
    Message_id    int64
    Parent_id     int64
    Show_parent   bool
    Message_Edits int8
    Message_Stars int8
}

type ChatEvents struct {
    Events []ChatEvent
    Time   int64
    Sync   int64
    Ms     int8
}

const (
    Mode         = "Messages"
    ChatUrl      = "http://chat.stackexchange.com/chats/8595/events"
    FKey         = "68f5a3ce293c47399c96ffcd85e0d280" // Go to the chat, F12, reload, look at the /events call and steal its fkey property
    MessageCount = 100                                // Never use this value directly: SE only uses it as a hint and might return a bit more when it feels like it
    Since        = 0
)

var (
    lastMessage int64
)

func main() {
    ticker := time.NewTicker(1 * time.Second)
    quit := make(chan struct{})

    for {
        select {
        case <-ticker.C:
            body := sendRequest()
            parsedJson := parseJson(body)
            newestMessages := getNewestMessages(parsedJson.Events)

            for i := 0; i < len(newestMessages); i++ {
                var currentMessage = newestMessages[i]
                if currentMessage.User_id == -263 || currentMessage.User_id == 125580 {
                    // Ignore Captain Obvious & Duga
                    continue
                }

                fmt.Printf("[%v] %s: %s\n",
                    time.Unix(currentMessage.Time_stamp, 0).Format("15:04:05"),
                    currentMessage.User_name,
                    currentMessage.Content)
            }
        case <-quit:
            ticker.Stop()
            return
        }
    }
}

func sendRequest() (content []byte) {
    response, err := http.PostForm(ChatUrl, url.Values{
        "mode":     {Mode},
        "msgCount": {strconv.Itoa(MessageCount)},
        "fkey":     {FKey},
        "since":    {strconv.Itoa(Since)}})

    if err != nil {
        fmt.Println("Error retrieving response")
        fmt.Println(err.Error())
        return nil
    }

    defer response.Body.Close()
    content, err = ioutil.ReadAll(response.Body)
    if err != nil {
        fmt.Println("Error reading response")
        fmt.Println(err.Error())
        return nil
    }

    return
}

func parseJson(body []byte) (parsedJson ChatEvents) {
    err := json.Unmarshal(body, &parsedJson)
    if err != nil {
        fmt.Println("Error parsing json")
        fmt.Println(err.Error())
        return
    }

    return
}

func getNewestMessages(events []ChatEvent) (output []ChatEvent) {
    output = make([]ChatEvent, 0)

    for index := 0; index < len(events); index++ {
        if events[index].Time_stamp > lastMessage {
            events[index].Content = html.UnescapeString(sanitize.HTML(events[index].Content))
            output = append(output, events[index])
            lastMessage = events[index].Time_stamp
        }
    }

    return
}


texts:
I have written a Java class to replace text in file.  The file contains database configurations and is as follows:

test.properties

#local
db.url=jdbc:oracle:thin:@localhost:test

#db.user=testa
#db.password=testa

db.user=testb
db.password=testb

#db.user=testc
#db.password=testc

# is a comment character. Now db schema testb is in use.

Here is my Java class to switch between schemas

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class SwitchTo
{
  public static void main(String[] args)
  {
    Map<String, String> schemaMap = new HashMap<String, String>();
    schemaMap.put("a", "testa");
    schemaMap.put("b", "testb");
    schemaMap.put("c", "testc");

    String newText = "";
    for (int i = 0; i < args.length; i++)
    {
      newText = args[i];
    }

    String newdb = "";
    newdb = schemaMap.get(newText);
    if (newdb == null || (newdb != null && newdb.length() <= 0))
    {
      System.out.println("Schema not available, please select : ");
      for (Map.Entry<String, String> entry : schemaMap.entrySet())
      {
        System.out.println(entry.getKey() + " for " + entry.getValue());
      }
      return;
    }

    try
    {
      BufferedReader file = new BufferedReader(new FileReader("test.properties"));
      String total = "";
      String line = "";
      while ((line = file.readLine()) != null)
      {
        if (!line.startsWith("#") && line.contains("db.user"))
        {
          line = "#" + line;
        }

        if (!line.startsWith("#") && line.contains("db.password"))
        {
          line = "#" + line;
        }

        if (line.startsWith("#") && line.contains(newdb))
        {
          line = line.substring(1);
        }

        total = total + line + "\n";
      }

      FileOutputStream File = new FileOutputStream("test.properties");
      File.write(total.getBytes());
      System.out.println("Switched to schema " + schemaMap.get(newText));
    }
    catch (FileNotFoundException e)
    {
      e.printStackTrace();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }
}

and I have created a batch file to run this program from command line which is as follows :

switch.bat
java SwitchTo %1

Now when write at command line

c:\> switch a

Then it will comment testb in the file and testa will be uncommented.

Please suggest other improvement for this code.

Is using map for storing schemas is a good choice?
How can I make it generic to accommodate newly added schemas without need to compile this class again?
Is there any better algorithm for solving this?


texts:
I want to store some objects in linear memory, but sometimes I want to use these objects in some place for some time, but in the meantime object can be deleted, so I want to use weak_ptr's. This is my idea how to handle this, what you think ?
Class which have vector of my object.

world3d.h

class World3d
{
public:
    void Render();
    std::weak_ptr<Object3d> CreateObject3d();

private:
    std::vector<Object3d> m_objects;
};

world3d.cpp

void World3d::Render()
{

}

std::weak_ptr<Object3d>  World3d::CreateObject3d()
{
    m_objects.emplace_back();
    return m_objects.back().GetWPtr();
}

void World3d::SetCamera(std::shared_ptr<Camera> pCamera)
{
    m_pCamera = pCamera;
}

object3d.h

class Object3d
{
public:
    Object3d();
    virtual ~Object3d();
    std::weak_ptr<Object3d> GetWPtr();

private:
    std::shared_ptr<Object3d> thisPtr;

    Matrix m_xform;
};

object3d.cpp

void null_deleter(Object3d *) {}
Object3d::Object3d()
{
    thisPtr.reset(this, &null_deleter);
}

Object3d::~Object3d()
{
}

std::weak_ptr<Object3d> Object3d::GetWPtr()
{
    return thisPtr;
}


texts:
Is there a more clever way of writing this piece of code? It does work but I thought there might be a better way of returning a matrix from multiplying the parameter by itself.

public static void Main(string[] args)
{
    int[,] m1 = CreateMatrix(5);
}

static int[,] CreateMatrix(int rowscols)
{
    int[,] result = new int[rowscols, rowscols];

    int res = rowscols * rowscols;
    int counter= 0;

    for (int i = 0; i < rowscols; ++i)
    {
        for (int k = 0; k < rowscols; ++k)
        {
            result[i, k] = (res - counter);
            counter += 1;
        }
    }

    return result;
}


texts:
I am new to programming and I would like some feedback. This is my first ruby program that simply adds a + b. I know it's probably more complicated than it needs to be, but I wanted to implement ideas that I was learning. Is there anything that I should do that I didn't or did that I shouldn't?

    puts "<<<-----ADDITION----->>>"
    puts "<<<------A+B=C------->>>"
    letters = %i(a b)
    sum = 0

    letters.each do |let|
      define_method(let) do
        begin
          puts "Enter #{let}"
          let = Float(gets.chomp)
          sum = sum + let.to_f
        rescue
      puts "Something went wrong. Try again."
      retry
    end
  end
end

letters.each do |let|
  send(let)
end

puts sum


texts:
Would this take \$O(n)\$ in worst case? Can it be improved?

var tree = {
  val: 5,
  left: {
    val: 2, left: null, right: null
  },
  right: {
    val: 6,
    left: null,
    right: {
      val: 8,
      left: null,
      right: null
    }
  }
};

function inorderReverse(node, cb) {
  if (node.right !== null) inorderReverse(node.right, cb);
  cb(node);
  if (node.left  !== null) inorderReverse(node.left,  cb);
}

// Find the kth largest element
var k = 1;
var count = 1;
inorderReverse(tree, function(node) {
  if (count++ === k) console.log(node.val);
});


texts: Grouping into more groups in one iteration

texts:
I had a need to group the same dataset in several groups. So instead of repeatedly query the dataset, I made an extension that could do it once. The caveat is, that the result is materialized in dictionaries, because I didn't managed to find an way to avoid that. Maybe you can?

public static IDictionary<string, Dictionary<object, HashSet<T>>> MultiGroupBy<T>(this IEnumerable<T> source, params (string Label, Func<T, object> Getter)[] groupers)
{
  if (source == null) throw new ArgumentNullException(nameof(source));
  if (groupers == null) throw new ArgumentNullException(nameof(groupers));

  IDictionary<string, Dictionary<object, HashSet<T>>> results = new Dictionary<string, Dictionary<object, HashSet<T>>>();

  using (var enumer = source.GetEnumerator())
  {
    while (enumer.MoveNext())
    {
      foreach ((var label, var func) in groupers)
      {
        if (!results.TryGetValue(label, out var dict))
        {
          dict = new Dictionary<object, HashSet<T>>();
          results[label] = dict;
        }

        var key = func(enumer.Current);
        if (!dict.TryGetValue(key, out var set))
        {
          set = new HashSet<T>();
          dict[key] = set;
        }

        set.Add(enumer.Current);
      }
    }

  }

  return results;
}

Use case:

static void TestMultiGrouping()
{
  string[] data =
  {
    "Black",
    "White",
    "Yellow",
    "green",
    "Red",
    "blue",
    "cyan",
    "Magenta",
    "Orange"
  };

  foreach (var result in data.MultiGroupBy(
    ("First UCase", s => s.Length > 0 && char.IsUpper(s[0])),
    ("Length", s => s.Length),
    ("Length Four", s => s.Length == 4),
    ("Contains 'e'", s => s.Contains('e')),
    ("Num n's", s => s.Count(c => c == 'n'))))
  {
    Console.WriteLine($"Results for {result.Key}:");
    foreach (var dict in result.Value)
    {
      Console.WriteLine($"{dict.Key}: {dict.Value.Count} [{(string.Join(", ", dict.Value))}]");
    }
    Console.WriteLine();
  }
}


texts: "Remember me" functionality for a website

texts:
I have read a few SO threads to implement remember_me functionality.

Steps I have followed:

User clicks on login button and if passes client side validation, it goes to php Login page.

First time

 function storeCookie($row,$connection)
 {
        $user_id = $row['UserID'];
        $token = uniqid($user_id,TRUE);
        $salt = md5(mt_rand());
        $cookie_id = hash_hmac('SHA512',$token,$salt);
        $expiry = strval(time() + (7 * 24 * 60 * 60));
        $cookie_name = "GETIN";
        $sql_store_cookie = "INSERT INTO pcookies(cookie_id,user_id,expiry,salt,cookie_name) values('$cookie_id','$user_id','$expiry','$salt','$cookie_name')";
        mysqli_query($connection,$sql_store_cookie) or die(mysqli_error($connection));//die('{"l":"mysqli_error(`$connection`)"}');
        setcookie("GETIN",$token,$expiry);
}

It reads user id from database[already user registered].
Creates a unique id and salt, hashed value. Sets expiration date for 7 days and store it in the database

cookie is [cookie_name=token]

All the times but not the first

Checks for cookie_name in the browser and if it is present reads the corresponding value
Using that name, gets the salt from database
Calculates has and checks with db
If success, go to the home page.

  if(isset($_COOKIE['GETIN']))
  {
    $cookie_name = 'GETIN';
    $salt = getSalt($cookie_name,$connection);
    $cookie_id = getCookieID($cookie_name,$connection);
    echo "      cookieid=".$cookie_id ;
    echo "      salt=".$salt;
    if($cookie_id == (hash_hmac('SHA512',$_COOKIE['GETIN'],$salt)))
    {
        die('{"status":"success"}');
    }
  }

It works fine. My doubts are

Is this method ok or need to modify something or everything. If so, please guide me
I didn't update the salt and hash once user successfully logged in. Do I need to update?
I am doing everything with PHP.

My site doesn't conatain any sensitive data like payments. It's just like tutorial site. Please share your few experiences with this functionality.

 function getSalt($cookie_name,$connection)
 {
    $sql_token_query = "select salt from pcookies where cookie_name = '$cookie_name'";
    $sql_token = mysqli_fetch_array(mysqli_query($connection,$sql_token_query));
    echo "   getSalt=".$sql_token['salt'];
    return $sql_token['salt'];
  }

  function getCookieID($cookie_name,$connection)
  {
    $sql_cookieid_query = "select cookie_id from pcookies where cookie_name = '$cookie_name'";
    $sql_cookieid = mysqli_fetch_array(mysqli_query($connection,$sql_cookieid_query));
    echo "   getCookie=".$sql_cookieid['cookie_id'];
    return $sql_cookieid['cookie_id'];
   }


texts:
So I've got this module called risar, which draws. But that's not really of importance. I wrote this code which sets 20 flowers on the background.

Now they need to move downwards by 5 units. The code works fine but it looks horribly awkward to me. I'd like it to look more "fancy" or maybe that less loops would be used or I'd like to see simply another way to do it. I need help with 2nd function; the 1st one looks okay. I'm relatively new to Python.

def doFlowers():
    flowers = []
    colors = ["black_flower.svg","blue_flower.svg", "brown_flower.svg", "green_flower.svg","purple_flower.svg"]
    for i in range(20):
        x = random.randint(20, (risar.maxX-20))
        y = random.randint(20, 300)
        flower = risar.picture(x, y, barve[i//4]) # 0, 1, 2, 3, 4
        flowers.append(flower)
    return flowers
flowers = doFlower()

def moving(flower):
    for i in range(len(flower)):
        while flower[i].y() < risar.maxY:
            for p in flower: #p is position
                p.setPos(p.x(), p.y()+5)


texts:
I sometimes have to schedule some tasks and wanted to have my own reusable scheduler. Since I like the Rx, I build it on top of it.

Follow-up
There is a newer version of the Scheduler.

The Scheduler class is really simple. It's backed by a newer implementation of my old CronExpression.
There are currently only these two methods. The factory method Create creates a new scheduler that ticks at the specified intervals and provides schedules as DateTimes to the observers.
Jobs are scheduled with the Schedule extension. This one requires a cron-expression and the action to execute.
public static class Scheduler
{
    public static IObservable<DateTime> Create(TimeSpan interval, IDateTime dateTime)
    {
        return
            Observable
                .Interval(TimeSpan.FromSeconds(1))
                .Select(_ => dateTime.Now());
    }

    public static IDisposable Schedule(this IObservable<DateTime> schedules, string cronExpressionString, Action<DateTime> action)
    {
        var cronExpression = CronExpression.Parse(cronExpressionString);
        return
            schedules
                .Where(cronExpression.Contains)
                .Subscribe(action);
    }
}

The DateTime abstraction is supported by the IDateTime interface:
public interface IDateTime
{
    DateTime Now();
}

which is implemented as
public class LocalDateTime : IDateTime
{
    public DateTime Now() => DateTime.Now;
}

or
public class UtcDateTime : IDateTime
{
    public DateTime Now() => DateTime.UtcNow;
}

Example
In order to use it I just create a scheduler, specify what kind of timestamp it should generate and schedule some actions:
var scheduler = Scheduler.Create(TimeSpan.FromSeconds(1), new LocalDateTime());

scheduler.Schedule("0/1 * * * * * *", schedule =>
{
    Console.WriteLine($"DEBUG: {schedule} [{Thread.CurrentThread.ManagedThreadId}]");
});

scheduler.Schedule("0/5 * * * * * *", schedule =>
{
    Console.WriteLine($"ACTION: {schedule}");
});

The output is:

DEBUG: 13/04/2018 22:32:09 [10]
DEBUG: 13/04/2018 22:32:10 [12]
ACTION: 13/04/2018 22:32:10
DEBUG: 13/04/2018 22:32:11 [10]
DEBUG: 13/04/2018 22:32:12 [14]
DEBUG: 13/04/2018 22:32:13 [8]
DEBUG: 13/04/2018 22:32:14 [12]
ACTION: 13/04/2018 22:32:15
DEBUG: 13/04/2018 22:32:15 [8]
DEBUG: 13/04/2018 22:32:16 [12]
DEBUG: 13/04/2018 22:32:17 [8]

There seems to be no rocket science here but this might elusive. Can/should this scheduler by improved in any way?


texts: Add elements to an array inside a foreach loop

texts:
I have the code below:

<?php

$i = array(1, 2, 3);

$w = array(1 => '11', 2 => '22', 3 => '33');

foreach ($i as $f) {
    $ws = $w[$f];

    $file_names[] = array(
        'fn' => 'fname',
        'sn' => 'sname',
        'is' => 'is',
        'rv' => 'rv'
    );

    foreach ($file_names as $k => $v) {
        if (!isset($file_names[$k]['mod'])) {
            $file_names[$k]['mod'] = array(
                'ct',
                'pt'
            );
        }

        if (!isset($file_names[$k]['pw'])) {
            $file_names[$k]['pw'] = array(
                'task'  => '3',
                'min'   => 'min',
                'max'   => 'max',
                'value' => "" . $ws . ""
            );
        }
    }
}

print_r($file_names);

?>

What I’m trying to do is add new elements to an array in some particular conditions. The only thing that I don’t like is the second foreach loop part. I.e.:

    foreach ($file_names as $k => $v) {
        if (!isset($file_names[$k]['mod'])) {
            $file_names[$k]['mod'] = array(
                'ct',
                'pt'
            );
        }

        if (!isset($file_names[$k]['pw'])) {
            $file_names[$k]['pw'] = array(
                'task'  => '3',
                'min'   => 'min',
                'max'   => 'max',
                'value' => "" . $ws . ""
            );
        }
    }

Is there any way to write this in a more elegant manner?


texts: Conditionally set strings if files exist

texts:
How can I reduce the lines I use with this code block?

if ((test.contains("1.jpg") || test.contains("1.png")) && (maxP == false)){
        page++;
        add = 1;
        if (QFile().exists(basepath + spage + ".jpg")){
            p_left = basepath + spage + ".jpg";
        }
        else if(QFile().exists(basepath + spage+ ".png")){
            p_left = basepath + spage + ".png";
        }
        if (QFile().exists(basepath + QString::number(page + 1) + ".jpg")){
            p_right = basepath + inc + ".jpg";
        }
        else if(QFile().exists(basepath + QString::number(page + 1) + ".png")){
            p_right = basepath + inc + ".png";
        }
    }
    else if ((test.contains("1.jpg") || test.contains("1.png")) && (maxP == true)){
        gpage = max;
        add = 1;
        if (QFile().exists(basepath + smax + ".jpg")){
            p_left = basepath + smax + ".jpg";
        }
        else if(QFile().exists(basepath + smax + ".png")){
            p_left = basepath + smax + ".png";
        }
        if (QFile().exists(basepath + QString::number(page + 1) + ".jpg")){
            p_right = basepath + sinc + ".jpg";
        }
        else if(QFile().exists(basepath + QString::number(page + 1) + ".png")){
            p_right = basepath + sinc + ".png";
        }
    }


texts: Date/Time picker for browsers that don't support the datetimelocal input

texts:
I have this code that shows date pickers when the browser doesn't support <input type="datetime-local">.
Any tips on optimizing this code?
if (!Modernizr.inputtypes.date) {
    $(function () {
        var d = Date.parse($('#StartDatePicker').val());
        $('#StartDatePicker').val($.format.date(d, "yyyy-MM-dd hh:mm a"));
        d = Date.parse($('#EndDatePicker').val());
        $('#EndDatePicker').val($.format.date(d, "yyyy-MM-dd hh:mm a"));

        var startDateTextBox = $('#StartDatePicker');
        var endDateTextBox = $('#EndDatePicker');
        startDateTextBox.datetimepicker({
            dateFormat: "yy-mm-dd",
            timeFormat: "hh:mm TT",
            minuteGrid: 10,
            addSliderAccess: true,
            sliderAccessArgs: {
                touchonly: false
            },
            onClose: function (dateText, inst) {
                if (endDateTextBox.val() != '') {
                    var testStartDate = startDateTextBox.datetimepicker('getDate');
                    var testEndDate = endDateTextBox.datetimepicker('getDate');
                    if (testStartDate > testEndDate) endDateTextBox.datetimepicker('setDate', testStartDate);
                } else {
                    endDateTextBox.val(dateText);
                }
            },
            onSelect: function (selectedDateTime) {
                endDateTextBox.datetimepicker('option', 'minDate', startDateTextBox.datetimepicker('getDate'));
            }
        });

        endDateTextBox.datetimepicker({
            dateFormat: "yy-mm-dd",
            timeFormat: "hh:mm TT",
            minuteGrid: 10,
            addSliderAccess: true,
            sliderAccessArgs: {
                touchonly: false
            },
            onClose: function (dateText, inst) {
                if (startDateTextBox.val() != '') {
                    var testStartDate = startDateTextBox.datetimepicker('getDate');
                    var testEndDate = endDateTextBox.datetimepicker('getDate');
                    if (testStartDate > testEndDate) startDateTextBox.datetimepicker('setDate', testEndDate);
                } else {
                    startDateTextBox.val(dateText);
                }
            },
            onSelect: function (selectedDateTime) {
                startDateTextBox.datetimepicker('option', 'maxDate', endDateTextBox.datetimepicker('getDate'));
            }
        });

    });
}


texts:
It is a simple semaphore in Java. Although it passes all their tests with flying colors, I'm still not sure it's correct.

For example, the last thing I wasn't sure about was mLock.lockInterruptibly(); vs mLock.lock(); in the method called aquire(). And I ended up using lockInterruptibly() because if the thread calling lockInterruptibly() is interrupted, then InterruptedException is thrown.

package edu.vuum.mocca;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;

/**
 * @class SimpleSemaphore
 *
 * @brief This class provides a simple counting semaphore
 *        implementation using Java a ReentrantLock and a
 *        ConditionObject (which is accessed via a Condition). It must
 *        implement both "Fair" and "NonFair" semaphore semantics,
 *        just liked Java Semaphores.
 */
public class SimpleSemaphore {
    /**
     * Define a ReentrantLock to protect the critical section.
     */
    // TODO - you fill in here
    ReentrantLock mLock;

    /**
     * Define a Condition that waits while the number of permits is 0.
     */
    // TODO - you fill in here
    Condition mCondition;

    /**
     * Define a count of the number of available permits.
     */
    // TODO - you fill in here.  Make sure that this data member will
    // ensure its values aren't cached by multiple Threads..
    volatile int mAvailable;

    public SimpleSemaphore(int permits, boolean fair) {
        // TODO - you fill in here to initialize the SimpleSemaphore,
        // making sure to allow both fair and non-fair Semaphore
        // semantics.
        mAvailable = permits;
        mLock = new ReentrantLock(fair);
        mCondition = mLock.newCondition();
    }

    /**
     * Acquire one permit from the semaphore in a manner that can be
     * interrupted.
     */
    public void acquire() throws InterruptedException {
        // TODO - you fill in here.
        try {
            mLock.lockInterruptibly();
            while (mAvailable == 0) {
                mCondition.await();
            }
            mAvailable--;
            mCondition.signalAll();
        } finally {
            mLock.unlock();
        }
    }

    /**
     * Acquire one permit from the semaphore in a manner that cannot be
     * interrupted.
     */
    public void acquireUninterruptibly() {
        // TODO - you fill in here.
        try {
            mLock.lock();
            while (mAvailable == 0) {
                mCondition.awaitUninterruptibly();
            }
            mAvailable--;
            mCondition.signalAll();
        } finally {
            mLock.unlock();
        }
    }

    /**
     * Return one permit to the semaphore.
     */
    void release() {
        // TODO - you fill in here.
        try {
            mLock.lock();
            mAvailable++;
            mCondition.signalAll();
        } finally {
            mLock.unlock();
        }
    }

    /**
     * Return the number of permits available.
     */
    public int availablePermits() {
        // TODO - you fill in here by changing null to the appropriate
        // return value.
        return mAvailable;
    }
}


texts:
I have a macro comprised of this and similar Subs. They work, but I feel like it's slowing it down. Two workbooks are open, and various ranges are copied from one that is hidden (wbSource) and pasted into the other (mainWB), which is not hidden. There is formatting in all the cells that need to be copied, not just the values. Is there a way to do this better?

Sub CopyData()
Dim mainWB  As Workbook
Dim mainWS  As Worksheet
Set mainWB = ActiveWorkbook
Set mainWS = mainWB.Sheets(1)

Dim wbSource As Workbook
Set wbSource = Workbooks.Open(Filename:="H:\Formatting.xlsx")
ActiveWindow.Visible = False

wbSource.Sheets(1).Range("A10:CX15").Copy
mainWS.Paste
Range("A1").Select
wbSource.Sheets(1).Range("A25:M26").Copy
mainWS.Paste
mainWS.Range("AF8").Select
wbSource.Sheets(1).Range("D49").Copy
mainWS.Paste
mainWS.Range("AF10").Select
wbSource.Sheets(1).Range("D51").Copy
mainWS.Paste

wbSource.Close
End Sub


texts:
I am trying to efficiently use the SEDE tool to get a list of tags a user has answered questions on, and their stats on each Tag.

My code works for my account in 3185 ms, but if I try to run it on @jon-skeet's, user ID (22656) then it times out.

Are there ways to make this more efficient / better code, and allow it to be used for any user ID?

Stack Explorer Link

-- The tags and scores of my posts
CREATE TABLE #MyPosts (
  _tags nvarchar(250) COLLATE SQL_Latin1_General_CP1_CS_AS,
  _score int
);

INSERT INTO #MyPosts
SELECT
  Question.Tags,
  Answers.Score
FROM
  Posts as Answers
INNER JOIN
  Posts AS Question
ON
  Question.Id = Answers.ParentId
WHERE
  Answers.PostTypeId = 2 AND
  Answers.OwnerUserId = ##UserId:int?8041461##;
--------------------------------------------------------------------------
-- All of the tags with the total score and the amount of times used
CREATE TABLE #TagCounts (
  _tagName nvarchar(35) COLLATE SQL_Latin1_General_CP1_CS_AS,
  _score int,
  _count int
);

INSERT INTO #TagCounts
SELECT
  Tags.TagName,
  sum(_score),
  count(*)
FROM
  #MyPosts
INNER JOIN Tags ON #MyPosts._tags LIKE '%<'+Tags.TagName +'>%'
GROUP BY Tags.Id,Tags.TagName;
--------------------------------------------------------------------------
-- Outputs the tags with links, total score, count and average score
SELECT
  _tagName as [TagName],
  _score as 'Total Score',
  _count as 'Answer Count',
  cast(_score as FLOAT) / _count as 'Average Score'
FROM
  #TagCounts
WHERE
  _score IS NOT NULL
ORDER BY
  _score DESC


texts: Different method to calculate blob area in OpenCv

texts:
I'm trying to use a different method to calculate a blob area from contourArea, using the countNonZero function. I want to see if there is significant approximation introduced by contourArea function, and also be able to calculate area of contour with auto-intersection.

cv::findContours(drawingIn, contoursIn, CV_RETR_TREE, CV_CHAIN_APPROX_NONE);

double max=0;
double currentarea=0;
int currentareaCounted = 0;
int maxAreaCounted = 0;

for (unsigned int i=0;i<contoursIn.size();i++)
{
    currentarea=cv::contourArea(contoursIn[i]);
    cv::Mat drawingMatCount = cv::Mat::zeros(ROI_INTERACTION,ROI_INTERACTION, CV_8UC1);
    cv::drawContours(drawingMatCount, contoursIn, i, 255, -1, 8);
    currentareaCounted = cv::countNonZero(drawingMatCount);

    if (currentarea>max)
        max=currentarea;
    if (currentareaCounted>maxAreaCounted)
        maxAreaCounted=currentareaCounted;

}

Is there something that could be improved? This code works, but my doubt is about declaring a new matrix every iteration. Could this lead to some performance issue?


texts:
Maybe a somewhat odd choice of language, but here is a program in ><> I have tried
to optimize the execution time of. (Not golfing). The efficiency is measured in the number of required instructions on an ideal ><>-machine, which uses the same amount of time to execute each instruction.

The program does a complete factorization of a number on the stack, and prints the result. The method used is trial division of odd numbers, up to the square root of the original number. The 2-factors are calculated first. The core of this program is the third line, which wraps around, and has a minimum of 2D-program flow commands. (I have also not used p, so the source code is static, and does not modify itself.)

An online interpreter for ><> is available here.

:?!;:2%?v2n2,30.
        >:3:02.
::*$}(?v::{:@%?!v2+
;n;?=1:<
,:r~:n:02.      >:@

Here is a commented version:

:?!;                   //Checks if n is 0. Sends the next part into an infinite loop if not dealt with

    :2%?v2n2,30.           //Loop that gets all factors of 2

        >:3:02.                //Escape condition executed when the number is no longer divisible by 2, go to main loop

::*$}(?v               //Main loop, the first condition checks if the candidate for trial division is > sqrt(n)

        ::{:@%?!v2+            //Checks divisibility by modulo, if not, increase candidate by 2

;n;?=1:<               //Prints the remainder as the last factor, except when it is 1

,:r~:n:02.      >:@    //When a factor is found, it is printed, n is divided, and the program goes back to the main loop

The program outputs the numbers directly, so for testing purposes, it may be convenient to separate them with commas:

:?!;:2%?v2n2,4b*o30.
        >:3:02.
::*$}(?v::{:@%?!v2+
;n;?=1:<
,:r~:n4b*o:02.  >:@

The main loop in detail:

The stack starts off with n,n,i ,where n is the number we are trying to factorize, and i is the iterator.

::*  //The iterator is copied two times, and mad into a square. n,n,i,s
$}   //The iterator is sent back to the bottom of the stack. i,n,n,s
(?v  //The square is compared with n. (both values are popped). If the square is larger or equal, the instructor goes down one line. i,n
::{: //n is copied two times, the iterator called to the top, and is copied too. n,n,n,i,i
@    //The three topmost values of the stack are rotated. n,n,i,n,i
%?!v //Takes the modulo of n and the iterator, if >0, the instructor jumps over the arrow down to the next line. n,n,i
2+   //Increments the iterator by two. The line wraps back to the beginning of the loop.

I would like to know if there are optimization opportunities I have missed, and if the code is fairly readable by ><> standards. Again, this is not about golfing or obfuscating the code.

If you are testing the code with the online interpretor, there is an easy way to put a number in the initial stack (Otherwise, you get the standard ><>-error "Something smells fishy...").


texts: To understand what recursion is, you must first understand recursion

texts:
This is the second assignment for my CS2 course:

  Write a recursive C++ function writeLine() that writes a character    repeatedly to form a line of n characters. For example:

writeLine('*', 5)

  produces the output:

*****

  Write a recursive [C++] function writeBlock() that uses writeLine    to write m lines of n characters each. For example,

writeBlock('*', 5, 3)

  produces the output:

*****
*****
*****

  Implement and test a recursive C++ function writePyramid(). The    function should take in a character to build a pyramid with and the
  height of the pyramid (the number of lines in it). Hint: Each line in
  the pyramid should be generated by two calls to writeLine: the first
  call generates the spaces and a second call to generate the line of
  characters.
     The ␣ in the output below represents a space character. This output    is generated when the function is asked to generate a
  pyramid of    height 3 with the * character.

␣␣*
␣***
*****

Please feel free to rip the code apart!  In my opinion, I think the switch in main() could be DRYed up a bit, but I wasn't sure how.

lab2.cpp:

#include <iostream>
#include <cstdio>
#include "lab2functions.h"

char getSanitizedChar()
{
  // absorb newline character (if existant) from previous input
  if('\n' == std::cin.peek()) std::cin.ignore();
  return std::tolower(std::cin.get());
}

int main()
{
  char type = '*';
  char shape = 'l';
  int rows = 0;
  int cols = 0;
  do
  {
    std::cout << "Enter shape you would like {(L)ine, (b)lock, (t)riangle}: ";
    std::cin >> shape;

    switch(shape)
    {
    case 'l':
      std::cout << "Enter number of columns: ";
      std::cin >> cols;
      std::cout << "Enter character to build with (*): ";
      type = getSanitizedChar();
      writeLine(('\n' == type ? '*' : type), cols);
      std::endl(std::cout);
      break;
    case 'b':
      std::cout << "Enter number of rows: ";
      std::cin >> rows;
      std::cout << "Enter number of columns: ";
      std::cin >> cols;
      std::cout << "Enter character to build with (*): ";
      type = getSanitizedChar();
      writeBlock(('\n' == type ? '*' : type), rows, cols);
      break;
    case 't':
      std::cout << "Enter number of rows: ";
      std::cin >> rows;
      std::cout << "Enter character to build with (*): ";
      type = getSanitizedChar();
      writePyramid(('\n' == type ? '*' : type), rows);
      break;
    default:
      std::cout << "Invalid option";
      break;
    }
    std::cout << "\nRun a calculation again (y/N): ";  // signify n as default with capital letter
  } while ('y' == getSanitizedChar());
}

lab2functions.h:

#ifndef LAB2FUNCTIONS_H
#define LAB2FUNCTIONS_H

#include <cstdint>

void writeLine(const char, const int8_t);
void writeBlock(const char, const int8_t, const int8_t);
void writePyramid(const char, const int8_t);

#endif

lab2functions.cpp:

#include <iostream>
#include "lab2functions.h"

void writeLine(const char c, const int8_t num)
{
  if (num > 0)
  {
    std::cout << c;
    writeLine(c, num - 1);
  }
}

void writeBlock(const char c, const int8_t m, const int8_t n)
{
  if (m > 0)
  {
    writeLine(c, n);
    std::endl(std::cout);
    writeBlock(c, m - 1, n);
  }
}

void writePyramid(const char c, const int8_t h)
{
  static int count;
  count++;
  if (h > 0)
  {
    writeLine(' ', (2 * h - 1) / 2);
    writeLine(c, (2 * count - 1));
    std::endl(std::cout);
    writePyramid(c, h - 1);
  }
  count = 0;
}


texts: Tic Tac Toe code could probably be optimized more

texts:
I recently got some help from Stack Overflow on my Tic-Tac-Toe code for the win conditions, but I think it could be optimized a little more. Any tips?

moves = [["1", "2", "3"],
         ["1", "2", "3"],
         ["1", "2", "3"]]
acc = 0
def win(letter):
  for i in range(3):
      if ((moves[i][0] == moves[i][1] == moves[i][2] == letter) or
          (moves[0][i] == moves[1][i] == moves[2][i] == letter)):
        print("~~~ " + letter + " WON!!! CONGRATS!!!! ~~~")
        quit()
  if (set(moves[i][i] for i in range(3)) == set([letter])):
      print("~~~ " + letter + " WON!!! CONGRATS!!!! ~~~")
      quit()
  if (set(moves[i][2-i] for i in range(3)) == set([letter])):
      print("~~~ " + letter + " WON!!! CONGRATS!!!! ~~~")
      quit()
  if (acc == 5):
      print("TIE YOU BOTH LOSE")
      quit()
def playerInput():
  global acc
  player1 = input("Where do you want to place your X, player 1? (row number, space, number)")
  moves[int(player1[0]) - 1][int(player1[2]) - 1] = "X"
  acc += 1
  win("X")
  player2 = input("Where do you want to place your O, player 2? (row number, space, number)")
  moves[int(player2[0]) - 1][int(player2[2]) - 1] = "O"
  boardDraw()
def boardDraw():
  print("1| "+moves[0][0]+" | "+moves[0][1]+" | "+moves[0][2]+" |")
  print(" |---+---+---|")
  print("2| "+moves[1][0]+" | "+moves[1][1]+" | "+moves[1][2]+" |")
  print(" |---+---+---|")
  print("3| "+moves[2][0]+" | "+moves[2][1]+" | "+moves[2][2]+" |")
  win("X")
  win("O")
  playerInput()
print("OK SO....\nPlayer 1 is X\nPlayer 2 is O\nGOOOOO!!")
boardDraw()


texts:
I am trying to generate Pascal's triangle table in Python 3. I started to like using this following pattern when dealing with 2D arrays.

Generate a list of valid indices
Use a function that works with those indices in a list comprehension. (may produce side effects)

I wonder, is this pattern pythonic and how common is it in practice?

def pascal_triangle(level):
    def compute(table, row, col):
        if row == 0:
            table.append([])
        if col == 0 or row == col:
            table[row].append(1)
        elif col <= row:
            table[row].append(table[row-1][col] + table[row-1][col-1])
    table = []
    valid_idxs = [(r,c) for r in range(level) for c in range(level)]
    [compute(table, r, c) for r, c in valid_idxs]
    print(table)


texts: Calculating the minimum distance of a linear code

texts:
This is a solution for the problem named Codes on the kattis platform:

  Given a generator matrix of a linear code, calculate the minimum distance of the code.

I'm looking for reviews on optimization and best practices. Code readability should be preserved.

public static class LinearCode {
   private int[][] generator;
   private int n;
   private int k;

   public LinearCode(int[][] generator, int n, int k) {
      this.generator = generator;
      this.n = n;
      this.k = k;
   }

   public int getMinimumDistance() {
      int minDistance = n;
      int maxKString = 1 << k;

      // generate all k-strings
      for (int i = 1; i < maxKString; i++) {
          int kstring = i;
          int distance = 0;

          // matrix multiplication
          for (int j = 0; j < n; j++) {
              int p = 0;
              for (int z = 0; z < k; z++) {
                  int a = generator[j][k-z-1];
                  int b = (kstring >>> z) & 1;
                  p = (p + a * b) & 1;
              }
              // distance as number if 1 bits
              distance += p;
          }

          minDistance = Math.min(minDistance, distance);
      }

      return minDistance;
   }
}