texts:
This is my RubyWarrior solution. I think RubyWarrior is well known to Ruby coders.  I am starting to learn Ruby and I would appreciate some help from you to improve the organization or the mistakes that I could have. I don't need another example as the Internet is full of them, but what I need is some advice that I can use as a beginner.

class Player
  attr_accessor :health, :direction, :n, :view, :warrior
  def initialize
    @health, @direction, @warrior  = health , direction , warrior
    @direction  = [:forward , :backward]
    @health, @view = [] , []
  end

  def play_turn(warrior)
    @health << warrior.health
    @view = warrior.look
    @backview = warrior.look :backward
    senses = warrior.feel @direction[@n]
      if ( senses.wall? && next_empty?(warrior) ) || senses.wall?
        warrior.pivot!
      elsif @backview[1].to_s.include?("Captive")
        warrior.walk! :backward
      elsif @backview[0].to_s.include?("Captive")
        warrior.rescue! :backward
      elsif next_empty?(warrior) && senses.stairs? || safe_step?
        warrior.walk!
        puts "Hero :D Finally I made it!"
      elsif senses.captive?
        warrior.rescue!
        puts "Hero ;)   feel free to face your destiny"
      elsif seek_and_shoot?
        warrior.shoot!
        puts "Hero >< BAAANNG!! Die already ranged scumbag"
      elsif warrior.health < 15 && safe?(warrior)
        warrior.rest!
        puts "Hero :(   I need to heal my wounds"
      elsif next_empty?(warrior)
        warrior.walk!
        puts "Hero :|   go go go!"
      else
        warrior.attack!
        puts "Hero :x   I will kill you evil #{warrior.feel.to_s.upcase}!"
      end

    life_bar_on_screen
    puts @view
    puts @backview
  end

  def loosing_life? warrior
    @health[-1] < @health[-2] ? true : false
  end

  def next_empty? warrior
    warrior.feel.empty?
  end

  def safe? warrior
    next_empty?(warrior) && !loosing_life?(warrior)
  end

  def life_bar_on_screen
    puts "_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ LIFE #{@health.last}"
    (1..@health.last).each { |x| print "▒ "}
    puts ""
  end

  def seek_and_shoot?
    foe = [ "Wizard" , "Archer", "Sludge"]
    o, oo, ooo = @view[0].to_s , @view[1].to_s , @view[2].to_s
    case
      when o == "nothing" && foe.include?(oo) then true
      #when o == "nothing" && ranged_foe.include?(oo) then true
      #when o == "nothing" && oo == friend then false
      when o == "nothing" && oo == "nothing" && foe.include?(ooo) then true
      else false
    end
  end

  def safe_step?
    friend = "Captive"
    o, oo, ooo = @view[0].to_s , @view[1].to_s , @view[2].to_s
    case
      when o == "nothing" && oo == friend then true
      when o == "nothing" && oo == "nothing" && ooo == friend then true
      else false
    end
  end

end

Shell output

CONGRATULATIONS! You have climbed to the top of the tower and rescued the fair maiden Ruby.
Level Score: 74
Time Bonus: 6
Clear Bonus: 16
Level Grade: A
Total Score: 503 + 96 = 599
Your average grade for this tower is: A

  Level 1: S
  Level 2: A
  Level 3: S
  Level 4: A
  Level 5: A
  Level 6: A
  Level 7: A
  Level 8: S
  Level 9: A


texts: Fetching all the project's items for a specific project id

texts:
In the following query, I am fetching all the projects items with specific project id. At the same time, I am using a join in Select to fetch the delivered quantity of items of this project only. The delivered quantity join feels very costly because if I have 7000 items, it will multiply the iterations. In there any better solution. It can be SQL related, backend programming or anything else.

SELECT
    msprojectitems.idJobItem,
    msprojectitems.project_id,
    msprojectitems.hashcode,
    msprojectitems.itemID,
    msprojectitems.itemName,
    msprojectitems.itemNum,
    msprojectitems.itemWeight AS totalWeight,
    msprojectitems.itemUnit,
    msprojectitems.deleted,
    msprojectitems.LastUpdated,
    msprojectitems.itemWeight_assigned AS assignedWeight,
    IFNULL(
        (
            SELECT
                Sum(
                    IFNULL(
                        msjobitems.itemWeight_loaded,
                        msjobitems.itemWeight
                    )
                ) AS quantity_delivered
            FROM
                msjobcustomer
            INNER JOIN msjobcusttoitems ON msjobcustomer.idJobCustomer = msjobcusttoitems.idJobCustomer
            INNER JOIN msjobitems ON msjobcusttoitems.idJobItem = msjobitems.idJobItem
            WHERE
                msjobcustomer.project_id = 10
            AND msjobitems.itemID = msprojectitems.itemID
            AND msjobcustomer.jobstatus = 1
            GROUP BY
                msjobitems.itemID
        ),
        0
    ) AS quantity_delivered
FROM
    msprojectitems
WHERE
    msprojectitems.project_id = 10
ORDER BY
    msprojectitems.itemID ASC

Result of Expanded Explain of this query:


texts:
I wrote this recently, I thought I'd check if it was the best way to keep my url as an https at all times, any advice would be appreciated

   if($_SERVER["HTTPS"] != "on")
{
    header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
    exit();
}


texts: Printing a list as "a, b, c." using Python

texts:
Is there a better way to do this? Assuming very long lists, is this slow and wasteful?

flavors = ['chocolate', 'vanilla', 'caramel', 'strawberry', 'coffee']

for flavor in flavors:
    print(flavor, end = ', ' if (flavors.index(flavor) != len(flavors) -1) else '.')

Output:

chocolate, vanilla, caramel, strawberry, coffee.


texts: Exception handling for a chain of prompts

texts:
I am trying to make an inputin() function to take all the parameters input for the first time with exception and for individual parameter for the runtime proposition. I am thus looking forward to reducing code size or being a more efficient coder with more pythonic procedures.

""This code is well executed and tested for all possible situations""

import turtle              # 1.  import the modules
#import random

BackGround = 'white'
Numside = 0
Armlen = 0
Turtlecolor = 'blue'
Turtleshape = 'turtle'

def inputin(count = 1, port = 0):
            #counting for resolving runtime error
    global BackGround, Numside, Armlen, Turtlecolor, Turtleshape

    while True :
        try :
            if((port == 0 or port == count) and count == 1):
                count+=1
                BackGround = str(input("Enter the Background Color : "))
            if((port == 0 or port == count) and count == 2):
                count+=1
                Numside = int(input("Enter the No. of Sides : "))
            if((port == 0 or port == count) and count == 3):
                count+=1
                Armlen = int(input("Enter the length of each side : "))
            if((port == 0 or port == count) and count == 4):
                count+=1
                Turtlecolor = str(input("Enter the Turtle Color : "))
            if((port == 0 or port == count) and count == 5):
                count+=1
                Turtleshape = str(input("Enter the Turtle Shape : "))
            port = -1
            break
        except ValueError :
            print("Oops!  That was no valid number.  Try again...")
            count+=-1

#Creating Screen after Everything Is Over

#i am creting this class for adjusting multiple values like a structure.
class Team(object):
    def __init__(self, Numside = 0, Armlen = 0, Turtlecolor = "", Turtleshape = ""):
        self.Numside = Numside
        self.Armlen = Armlen
        self.Turtlecolor = Turtlecolor
        self.Turtleshape = Turtleshape

def screen():
    wn = turtle.Screen()       # 2.  Create a screen

    while True:
        try:
            wn.bgcolor(BackGround)
            break
        except turtle.TurtleGraphicsError as e:
            inputin(1,1)

    wn.exitonclick()

def TurtleCreation():
    lance = turtle.Turtle()
    while True:
        positionInput = 0 #for marking the position of the desired input
        try:
            positionInput = 4
            lance.color(Turtlecolor)
            positionInput = 5
            lance.shape(Turtleshape)
            break
        except turtle.TurtleGraphicsError as f:
            inputin(positionInput,positionInput)
    lance.speed(500)
    lance.penup()
    #lance.goto(-300,200)

inputin()
TurtleCreation()
screen()

#sc = turtle.ScrolledCanvas(master)

#now shifting the turtle to the middle of the system


texts: Generating a list (or a string) with random elements

texts:
During implementation and testing of different small hobby projects I often reach the point where I need (at least I like it more) some random data beyond the usual foo-bar strings or lists. Random here does not mean really mathematical random data but just something that looks random to humans.

Therefore I came up with the following:

;;;; random.lisp
;;; Time-stamp: <2019-05-27 14:53:38 m.buchmann>
;;;
;;; A short sketch of some random data generating functions.
;;;

(ql:quickload "alexandria")

;; * Choosing a random element from a given list.
(defun random-draw (list &aux (len (length list)) (pos (random len)))
  "Returns a random element from LIST."
  (nth pos list))

;;; * Generating a random element
(defun random-element (type &key (radix 10) (case :up))
  "Returns a random element of type :digit (depending on :radix) or
  :character (case given by :case :up, :down or :both). Limited to
7bit ASCII characters from A to z."
  (let ((char-range (ecase case
                      (:up   (alexandria:iota 26 :start 65))
                      (:down (alexandria:iota 26 :start 97))
                      (:both (append (alexandria:iota 26 :start 65)
                                     (alexandria:iota 26 :start 97))))))
      (ecase type
        (:digit (random radix))
        (:character (code-char (random-draw char-range))))))

(defun random-list (len &key (type :digit) (radix 10) (case :up))
  "Returns a list of length LEN filled with random elements of TYPE :digit or :character."
  (loop :for i from 0 below len
        :collect (random-element type :radix radix :case case)))

(defun random-string (len &key (case :up) &aux (result (make-array len :element-type 'character)))
  "Returns a random string of length LEN and :case (:up, :down or :both)."
  (loop :for i :from 0 :below len
        :do (setf (aref result i) (random-element :character :case case)))
  result)

I did not pack it in a proper package etc. yet because my use case is pretty simple and usually temporary. I was wondering if other people have implemented similar things or if the need I felt was just so individual that no one else really cares about it. I did not find other libraries for this.

I think it could be easily extended to supply random-arrays, hash-tables and so on. Also the character encoding could be improved to deliver more than 7bit ASCII and this in a portable way.

Any comments on the usability, style etc. are gratefully acknowledged.


texts: Animation that cycles through background colors

texts:
I am doing a background image animation using the function. It works, but I think I am doing more coding than what it requires. Can anyone please help me to minimize it?

Don't recommend the CSS animations, I am working for IE9.

Live

var call = function () {

var x = 0;

    return function () {
        x++;
        x = x > 4 ? x=1 : x;
    $('#small').prop('class','').addClass('s'+x)
    .text(x)
    .animate({opacity: 0}, 3000, function() {
        call();
    });

        var y = x+1;

        $('#big').prop('class','').addClass('s'+y);

        $('#small').css({
            opacity:1
        })

    }

}();

call();
#big {
    width: 100px;
    height: 100px;
    position:relative;
    color:#fff;
  }

#small {
    position:absolute;
    left:0;
    top:0;
    width:100%;
    height:100%;
    color:#fff;
}

.s1,
.s5{
    opacity:1;
    background:gray;
}

.s2 {
    background:blue;
    opacity:1;
}

.s3 {
    background:yellow;
    opacity:1;
    color:#000;
}
.s4 {
    background:brown;
    opacity:1;
}


texts:
On my webform, there are two kinds of address-fields a user can give. But since it's a complex webform (Drupal) it's kind of hard to achieve. Every time a user adds an extra address, the form is regenerated and there will be a new item added to the $address_afl and $address_bev-array. Is it possible to compress this code so the foreach-loop starts looping with the highest value (either $address_afl or$address_bev )

$address_afl = $form['field_afl_dienst_adressen']['und'];
$i = 0;
foreach($address_afl as $value) {
    if (is_array($value)) {
        $test = array_keys($value);
    if(is_array($test)) {
        foreach ($test as $z) {
            if (strpos($z, '#') === 0) continue;
            if (isset($form['field_afl_dienst_adressen']['und'][$i][$z])) {
                $form['field_afl_dienst_adressen']['und'][$i][$z]['#prefix'] = "
";
                $form['field_afl_dienst_adressen']['und'][$i][$z]['#suffix'] = "
";
            }
        }
    }
    }
    $i++;
}

$address_bev = $form['field_bevoegde_adressen']['und'];
$i = 0;
foreach($address_bev as $value) {
    if (is_array($value)) {
        $test = array_keys($value);
    if(is_array($test)) {
        foreach ($test as $z) {
            if (strpos($z, '#') === 0) continue;
            if (isset($form['field_afl_dienst_adressen']['und'][$i][$z])) {
                $form['field_bevoegde_adressen']['und'][$i][$z]['#prefix'] = "
";
                $form['field_bevoegde_adressen']['und'][$i][$z]['#suffix'] = "
";
            }
        }
    }
    }
    $i++;
}


texts: Show dialog only once. Other calls should bring dialog to front, but otherwise not have a result

texts:
This code works, as far as I can tell, but there's something that just feels wrong about it. The intended flow is like this:

If no dialog is showing

Show dialog, return result

else

Move dialog into view, return no result

It sounds easy enough, but because there's a possiblity of multiple threads I have to use locking. However, because the ShowDialog() call is blocking, I couldn't just throw a lock around the whole thing, so instead my code is littered with Monitor.Enter and Monitor.Exit calls. It gets even more complicated due to exception handling.

interface IDialogService
{
    bool? ShowAuthenticationDialog();
}

class DialogService : IDialogService
{
    private readonly IServiceProvider _serviceProvider;

    public DialogService(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    private readonly object _authenticationDialogLock = new object();
    private bool _isAuthenticationDialogShowing;
    private AuthenticationDialog _authenticationDialog;

    public bool? ShowAuthenticationDialog()
    {
        Monitor.Enter(_authenticationDialogLock);
        if (!_isAuthenticationDialogShowing)
        {
            try
            {
                _isAuthenticationDialogShowing = true;
                _authenticationDialog = _serviceProvider.GetService<AuthenticationDialog>();
                Monitor.Exit(_authenticationDialogLock);

                var authenticationDialogResult = _authenticationDialog.ShowDialog();

                Monitor.Enter(_authenticationDialogLock);
                return authenticationDialogResult;
            }
            catch
            {
                return null;
            }
            finally
            {
                _authenticationDialog = null;
                _isAuthenticationDialogShowing = false;

                // Need this check because an exception could come from ShowDialog()
                // where we're not locked.
                if (Monitor.IsEntered(_authenticationDialogLock))
                    Monitor.Exit(_authenticationDialogLock);
            }
        }

        _authenticationDialog.Activate();
        Monitor.Exit(_authenticationDialogLock);
        return null;
    }
}

Can I make this less "messy" somehow? Have I missed any obvious cases where the constant grab-and-release of the lock can lead to problems?

I feel like there could be an edge case where a thread can call Activate() before ShowDialog() has been called or after it has returned, but I honestly can't think of how to protect against that specific case because ShowDialog() is blocking and thus has to release its lock.

Oh, and if anyone's wondering, the GetService<>() method on the IServiceProvider is an extension method that looks like this:

public static class ServiceProviderExtensions
{
    public static T GetService<T>(this IServiceProvider serviceProvider)
    {
        return (T)serviceProvider.GetService(typeof(T));
    }
}


texts:
I've written the following extension to determine the MIME type of a base64 string.  It's worked in my local tests, but can anyone point out issues or alternate methods?

public static AttachmentType GetMimeType(this string value)
{
    if(String.IsNullOrEmpty(value))
        return new AttachmentType
                {
                    FriendlyName = "Unknown",
                    MimeType = "application/octet-stream",
                    Extension = ""
                };

    var data = value.Substring(0,5);

    switch (data.ToUpper())
    {
        case "IVBOR":
        case "/9J/4":
            return new AttachmentType
                {
                    FriendlyName = "Photo",
                    MimeType = "image/png",
                    Extension = ".png"
                };

        case "AAAAF":
            return new AttachmentType
                {
                    FriendlyName = "Video",
                    MimeType = "video/mp4",
                    Extension = ".mp4"
                };
        case "JVBER":
            return new AttachmentType
                {
                    FriendlyName = "Document",
                    MimeType = "application/pdf",
                    Extension = ".pdf"
                };

        default:
            return new AttachmentType
                {
                    FriendlyName = "Unknown",
                    MimeType = string.Empty,
                    Extension = ""
                };
    }
}

public class AttachmentType
{
    public string MimeType { get; set; }
    public string FriendlyName { get; set; }
    public string Extension { get; set; }
}


texts: SSO login & authenticate Wordpress users with JWT token

texts:
I'm in the midst of exploring SSO with JWT & Wordpress, I'm not too sure if it's a good practice or does this setup/flow have any security vulnerabilities.

Currently JWT/SSO method i'm using is based on this answer/method which is getting JWT token using iFrame method instead of redirection method eg: from domain1.com > sso.com (retrieve JWT) > domain1.com

Please refer below for my setup/codebase fmi:

Main SSO domain (using Wordpress and JWT)

https://sso.com/login
https://sso.com/validation

Platform 1 (using plain PHP)

https://domain1.com

Platform 2 (using plain PHP)

https://domain2.com

sso.com/login (Wordpress)

Passport

<input type="text" name="username" value="admin"/>

<input type="text" name="password" value="admin"/>

Submit

Platform 1 & Platform 2 (PHP)

Questions: is it safe if i'm using postMessage to retrieve JWT token from iframe/sso.com? Any security vulnerability i need to concern?

    <meta charset="UTF-8">
    <title>Platform 1</title>

sso.com/validation (Wordpress)

Questions: Since we'll have multiple platform eg: domain1.com, domain2.com, etc, is it a good practice to pass a dynamic parameter in postMessage function using parentUrl?

tldr; is this the right direction to create SSO/JWT authentication with cross domains with PHP? is above method is a secure way to code it?


texts:
I have a date control which has a dropdown for each date, month and year.

The issue is, I can select 31st Nov. 2015 as well, and when I create date object, I get 1st Dec. 2015.

Example

var _date = 31; // value fetched from dropdown
var _month = 10;
var _year = 2015;

var date = new Date(_year, _month, _date);
document.write(date)

I want to validate this condition, and my current approach is to match date.getDate() with _date and show an error message if they are different.

Is there a better way to implement this?

Code

var _monthList = [
    {id:"1",name:"January"} ,
    {id:"2",name:"February"} ,
    {id:"3",name:"March"} ,
    {id:"4",name:"April"} ,
    {id:"5",name:"May"} ,
    {id:"6",name:"June"},
    {id:"7",name:"July"} ,
    {id:"8",name:"August"} ,
    {id:"9",name:"September"} ,
    {id:"10",name:"October"} ,
    {id:"11",name:"November"} ,
    {id:"12",name:"December"}];

function createYears(){
 var _year = [];
    for (var i = 2000; i<=new Date().getFullYear(); i++){
     _year.push({id:i, name:i});
    }
    $("#cbYear").html(createOptions(_year));
}

function createMonths(){
 $("#cbMonth").html(createOptions(_monthList));
}

function createDates(){
 var _dates = [];
    for (var i=1; i<=31; i++){
     _dates.push({id:i, name:i});
    }
    $("#cbDate").html(createOptions(_dates));
}

function createOptions(dataset){
 var optionStr = "<option></option>";
    $.each(dataset, function(key, value){
        var id = value.id? value.id:key;
        var text = value.name;
        var val = value.value?value.value:value.id;
        optionStr += "<option id="+ id + " name='"+ text+ "' value='"+ val + "'>"+ text + "</option>"
    });
    return optionStr;
}

function registerEvents(){
 $("select").on("change", function(e){
     validateDate();
    });
}

function validateDate(){
 var _date = $("#cbDate option:selected").val();
    var _month = $("#cbMonth option:selected").val();
    var _year = $("#cbYear option:selected").val();
    if(_year && _month && _date){
        var dateObj = new Date(_year, _month-1, _date);
        if(_date != dateObj.getDate()){
            $("#lblError").text("Please Select a valid date");
        }
        else{
         $("#lblError").text("");
        }
    }
}

(function(){
 createYears();
    createMonths();
    createDates();
    registerEvents();
})()
select{
    background:#fff;
    color:blue;
    width:100px;
    padding:5px;
    border-radius:4px;
    border: 1px solid gray;
}

.error{
    color:red;
}

<select id="cbYear"></select>
<select id="cbMonth"></select>
<select id="cbDate"></select>

Use Case

Select: Invalid Date (e.g. 31st Nov.)

I have also created a JSFiddle for the same.


texts: Create a matrix where if an element in an M×N matrix is 0, its entire row and column are set to 0

texts:
How is my implementation? Are there improvements I can make to the variable names or any edge cases I might have missed?

public class ZeroMatrix {
    public static void main(String[] args) {
        int[][] matrix = new int[][]{
                {1, 0, 2},
                {3, 4, 1}
        };
        System.out.println(Arrays.deepToString(setZeroes(matrix)));
    }

    private static int[][] setZeroes(int[][] matrix) {
        boolean[] rowsWithZero = new boolean[matrix.length];
        boolean[] columnsWithZero = new boolean[matrix[0].length];

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (matrix[i][j] == 0) {
                    rowsWithZero[i] = true;
                    columnsWithZero[j] = true;
                }
            }
        }
        // Iterate through the rowsWithZero array and transform all rows with 0 to 0
        for (int i = 0; i < rowsWithZero.length; i++) {
            if (rowsWithZero[i]) {
                transformRow(i, matrix);
            }
        }

        // Iterate through columnsWithZero and transform all columns with 0 to 0.

        for (int i = 0; i < columnsWithZero.length; i++) {
            if (columnsWithZero[i]) {
                transformColumn(i, matrix);
            }
        }

        return matrix;

    }

    private static void transformColumn(int column, int[][] matrix) {
        for (int row = 0; row < matrix.length; row++) {
            matrix[row][column] = 0;
        }
    }

    private static void transformRow(int row, int[][] matrix) {
        for (int column = 0; column < matrix[0].length; column++) {
            matrix[row][column] = 0;
        }
    }
}


texts:
this is my 2nd project on Python. I created a game of Noughts and Crosses(Tic-Tac-Toe) that you can play against the computer. What are your thoughts on my implementation of the game? Is there anything I've missed or could improve upon?
I did think about adding a figure window and making it more interactive by clicking on where you want to move however that seemed a bit too advanced.
import random
import sys
import numpy as np

# Today we are going to make an interactive game in Python.
# This is going to be a game of noughts and crosses!

#  Initialise grid and collection of X's or O's needed to win a game.
grid = [["_", "_", "_"], ["_", "_", "_"], ["_", "_", "_"]]
print(np.asarray(grid))  # To make the output represent a grid instead of a list of lists.
row_os = ["O", "O", "O"]
row_xs = ["X", "X", "X"]
coords_picked = []

# Create a loop to find all co-ordinates in our grid
all_coords = []
for x in range(3):
    for y in range(3):
        all_coords.append((x, y))

turn = 0
remaining_coords = []

while turn < 10:
    # Find status of each column
    column_1 = [row[0] for row in grid]
    column_2 = [row[1] for row in grid]
    column_3 = [row[2] for row in grid]

    # Find status of 2 diagonals
    main_diag = [row[i] for i, row in enumerate(grid)]
    counter_diag = [row[-i - 1] for i, row in enumerate(grid)]

    # Winning conditions for each player
    if (grid[0] == row_os or grid[1] == row_os or grid[2] == row_os) or (
        column_1 == row_os or column_2 == row_os or column_3 == row_os) or (main_diag == row_os) or (
        counter_diag == row_os):
        print("The computer has won!")
        sys.exit()
    elif (grid[0] == row_xs or grid[1] == row_xs or grid[2] == row_xs) or (
        column_1 == row_xs or column_2 == row_xs or column_3 == row_xs) or (main_diag == row_xs) or (
        counter_diag == row_xs):
        print("Well done, you have won!")
        sys.exit()
    else:
        # If nobody has won yet, take another turn
        if turn % 2 == 0:
            x_coord = input()
            y_coord = input()
            coords_picked.append((int(x_coord), int(y_coord)))
            grid[int(x_coord)][int(y_coord)] = "X"
            print(np.asarray(grid))
            turn += 1
        else:
            # Computer randomly picks a co-ordinate in the grid that has not been picked yet
            remaining_coords = list(set(all_coords) - set(coords_picked))
            comp_coords = random.choice(remaining_coords)
            grid[comp_coords[0]][comp_coords[1]] = "O"
            coords_picked.append((comp_coords[0], comp_coords[1]))
            print(comp_coords)
            print(np.asarray(grid))
            turn += 1

print("A draw?! We must play again!")


texts: Python program to check if a set of points is at land or at sea

texts:
I have written a program that divides an geographical area up in cells with size 0.002 degrees longitude by 0.001 degrees latitude, and check every cell whether it's a land area or a sea area. I've done this to effectively to get all the sea area of that area. This is probably insane from a GIS standpoint. Please review my code, call me an insane idiot and help me to get it better.

"""Function to iterate with decimal step size"""
def seq(start, end, step):
    assert(step != 0)
    sample_count = abs(end - start) / step
    return itertools.islice(itertools.count(start, step), sample_count)

if __name__ == "__main__":
    bottomlat = 70.390829
    toplat = 70.855549
    bottomlong = 27.692793
    toplong =  28.728254
    gridsize = 0.001
    map = Basemap(
    projection="merc",
    resolution = 'h', area_thresh = 0.001,
    llcrnrlon=bottomlong, llcrnrlat=bottomlat,
    urcrnrlon=toplong, urcrnrlat=toplat)
    map.drawcoastlines(color='black')
    """Divide global area into grid cells"""
    for i in seq(bottomlat, toplat, gridsize):
        for j in seq(bottomlong, toplong, gridsize*2):
            lon, lat = map(j,i)
            if not map.is_land(lon,lat):
                plt.scatter(lon,lat, s=0.1, color='c', edgecolors='none')
    plt.show()

The ultimate use case is:
I've god millions of lat/long positions from ships. I want to see how large percentage of the sea that has a lat/long position from a ship (cells with a ship position divided by total cell of ocean). So my initial thought was to check each cell if its sea, then perform a check if there is a ship position there.


texts:
Given a collection of numbers that might contain duplicates, return
  all possible unique permutations.

  For example, [1,1,2] have the following unique permutations:
  [[1,1,2], [1,2,1], [2,1,1]]

There are many better solutions out there but I am interested in just the code review and how it can be made better.

Solution is exactly described here

Let's use input abc as an example.

Start off with just the last element (c) in a set (["c"]), then add the second last element (b) to its front, end and every possible positions in the middle, making it ["bc", "cb"] and then in the same manner it will add the next element from the back (a) to each string in the set making it:

"a" + "bc" = ["abc", "bac", "bca"]  and  "a" + "cb" = ["acb" ,"cab", "cba"]
Thus entire permutation:

["abc", "bac", "bca","acb" ,"cab", "cba"]

class Solution(object):
    def permuteUnique(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        if not nums or len(nums) == 1:
            return [nums]
        output_list, output_list_copy, temp_output = [], [], []
        for num in nums:
            if not output_list:
                output_list = [[num]]
                continue
            for t in output_list:
                assigned, already_seen = False, None
                for j in range(len(t)+1):
                    if already_seen == num and assigned:
                        continue
                    t1 = t[0:j] + [num] + t[j:]
                    if j < len(t) and t[j] == num:
                        assigned, already_seen = True, num
                    temp_output.append(t1)
                output_list_copy += temp_output
                temp_output = []
            output_list = output_list_copy
            output_list_copy = []
        return output_list


texts: errorlocation() routine, implemented in C++ based on pseudocode

texts:
Recently I was reading a book called Code Complete by Steve McConnell and I came across a chapter called The PseudoCode Programming Process(PPP) where the chapter taught me on how to write Pseudo code and gave guidelines on how to convert that pseudo code to real code. That chapter inspired me a lot and I decided to follow that technique for writing all of my code. Inspired from the example given in the book I tried to write a simple routine that nearly follows those guidelines. Can you guys help me out on whether I am going in the right direction after looking the code below.

Here is the Pseudo code and real code that I wrote for a function called getErrorLocation that basically returns the coordinates of where the error occurred in a piece of code while parsing it.

Pseudo Code:

This routine outputs coordinate of error location found in gml code in
x/80 format based on the startlocation and currentlocation as supplied
by the calling routine. Also it outputs a error state indicating whether
the operation was successful
or not.

Set default value of error to FAIL

*Precondition
IF currentlocation<startlocation
    return FAIL
Calculate distance by subtracting currentlocation from startlocation
Divide distance by 80 and set the rownumber and colnumber to quotient and remainder of the division result respectively.
Set errorstate to SUCCESS
return coordinate with errorstate

Here is the C++ code written from the Pseudo Code given above

#include<iostream>
#include<cstdlib>

struct Point
{
    int x;
    int y;

};

/*This routine outputs coordinate of error location found in gml code in
x/80 format based on the startlocation and currentlocation as supplied by
the calling routine. Also it outputs a error state indicating whether the operation
was successful or not.*/

template<typename Iter>
std::pair<Point, bool>getErrorLocation(Iter locationcurrent, Iter locationstart)
{

    //Set default value of errorstate to FAIL
    bool error = true;

    //*Precondition

    //IF currentlocation<startlocation
    if (locationcurrent < locationstart)
        // return FAIL
        return { {0,0},error };

    //Calculate distance by subtracting currentlocation from startlocation
    int distance = locationcurrent - locationstart;

    //Divide distance by 80 and set the rownumber and colnumber to quotient and remainder of the division result respectively.
    auto [rownum, colnum] = div(distance, 80);
    //Set errorstate to SUCCESS
    error = false;
    //return coordinate with errorstate
    return { {rownum,colnum},error };
}

The main thing I want to highlight here are the comments that were actually the Pseudo code itself. I read in Clean Code by Robert C Martin that comments are harmful for the code and must be used to the minimum. I clearly understand why they are harmful, but I like this method also. Advantages weigh more I think for comments rather than their disadvantages. I feel like writing comments helps novices like me to understand the idea in the first glance itself rather than digging into the technical details and figuring out the code's real purpose. So now I am in a complete dilemma. There are contradictory statements from two of my favorite books.

What should I do?


texts: Recursive brute-force approach to maximum points you can obtain from cards

texts:
I came across this question on Leetcode. The question description is as follows:

There are several cards arranged in a row, and each card has an associated number of points.
The points are given in the integer array cardPoints. In one step, you can take one card from the beginning or from the end of the row.
You have to take exactly k cards. Your score is the sum of the points of the cards you have taken.
Return the maximum score you can obtain.
Sample testcases
cardPoints = [1,2,3,4,5,6,1], k = 3 => Output is 12
cardPoints = [2,2,2], k = 2 => Output is 4
cardPoints = [9,7,7,9,7,7,9], k = 7 => Output is 55
cardPoints = [1,1000,1], k = 1 => Output is 1

After looking at the discussion forums, I realized that this could be converted into a sliding window problem where we have to find the smallest subarray sum of length len(cardPoints) - k.
While I do understand this,
The initial method I tried was brute-force recursive and using dynamic programming to cache intermediate results. Despite this, it still results in a timeout. Is there any other optimization I can make to make my code run faster using this approach?
class Solution {
public:
    int maxScoreUtil(int left, int right,vector<int>& cardPoints, int k,vector<vector<int>>& dp){
        if(k == 0 || left == cardPoints.size() || right < 0)
            return 0;

        if(dp[left][right] != -1)
            return dp[left][right];

        int val_1 = maxScoreUtil(left+1,right,cardPoints,k-1,dp) + cardPoints[left];
        int val_2 = maxScoreUtil(left,right-1,cardPoints,k-1,dp) + cardPoints[right];

        return dp[left][right] = max(val_1,val_2);
    }

    int maxScore(vector<int>& cardPoints, int k) {
        int n = cardPoints.size();
        vector<vector<int>> dp(n+1, vector<int>(n+1, -1));
        return maxScoreUtil(0,n-1,cardPoints,k,dp);
    }
};I

Before using DP => 16/40 test cases passed followed by TLE
After using DP => 31/40 test cases passed followed by TLE


texts: Creating a secure and efficient DB connection and queries (using one class)

texts:
Currently, I'm working with a PHP database connection class that is in one single file with a construct. Every time I need this connection, I instantiate the class and the construct creates the connection with only having to modify the user, password, DBname and host.

It works fine and I haven't faced any problems with this class. Although I want to start taking security seriously in my web applications, I've been looking for a way to implement security (SQL Inj, XSS, DoS, etc.) and use updated functions, prepared statements, escaping, etc. My problem is that I haven't found a single answer about this exactly because I don't call the mysqli_connect function in index.php. I just create the object for the Connection class and use it.

<?php
    class Connection {
     private $connection;

     private $host='localhost';
     private $user='user';
     private $pass='pass';
     private $database='dbname';
     private $n=0;

    function __construct() {
        $this->connection = mysqli_connect($this->host, $this->user, $this->pass, $this->database);

        mysqli_query($this->connection,"SET NAMES 'utf8'");
    }

    function sql($sql) {
        if (is_array($sql)) {
            foreach ($sql as $s) {
                $res = mysql_query($s);
                if (mysql_errno()) echo mysql_error().'
';
                $this->n++;
            }
        } else {
            $res = mysqli_query($this->connection,$sql);
            if (mysql_errno()) echo mysql_error().'
';
            $this->n++;
        }
        return $res;
    }

    function __destruct() {
        if (is_resource($this->connection) )
        mysql_close($this->connection);
    }

    function getLink() {
        return $this->connection;
    }
}

So if I want to Create, Read, Update, Delete Something I do this in another file: User.php (Which i want to use the new method I'm asking for and use prepared statements for the Queries here and escape functions)

<?php
  // Declare a variable
     private $user;

  // Setter
     function setUser($val){
        $this->user = $val;
     }

  // Create Function to CreateUser
     function CreateUser(){
        $con = new Connection();
        $sql = "INSERT INTO user (DATA) VALUES(DATA)";
        $con->sql($sql);
     }

  // Same for all CRUD i just change the Query of course.

?>

<?php
  // At the index.php i do this:
  include_once 'User.php';

  $user = new User();

  if(isset($_POST['createUserButton'])){
     // $The variable i set in my User Class
     $user = $_POST['user'];

     // Then the Setter
     $user->setUser($user);

     // Then execute the Function
     $user->CreateUser();
  }
?>

I'm trying to translate this class using:

New versions of functions
Using try/catch
Security

I'm just trying to have as many points of view from more experienced developers. I'm a few months old at this and I'm trying to look at different methods to code so I can create my own.


texts: Match all youtube links in a string of text

texts:
I'm looking to pull all the youtube links from a string of text and was wondering how does this look?

if (preg_match_all('/(https?:\/\/)?(www\.)?(youtube\.com)\/watch\?v=([a-zA-Z0-9_-]+)[^\s]*/im', $this->content, $matches)) {

}

Obviously this doesn't take into account the youtu.be links as they are formatted differently.


texts: Improving performance of VBA batch scripts?

texts:
I am using a script to open a bunch of Excel files, copying two or more sheets into a new file and saving this new file. It sure beats doing it manually, but I think it could be faster.

Here's my script:

Sub Flujo()

Const FilePath = "A path..."
Const Destination = "Another path..."

Dim app As New Excel.Application
app.Visible = False
app.ScreenUpdating = False
app.DisplayAlerts = False

Dim str As String
str = Dir(FilePath & "\*.xlsx")
Do Until str = ""

    Dim WrkBook As Workbook
    Set WrkBook = app.Workbooks.Open(Filename:=FilePath & "\" & str, UpdateLinks:=0)
    str = Dir()

    Dim NewBook As Workbook
    Set NewBook = app.Workbooks.Add

    WrkBook.Sheets("SheetName").Copy After:=NewBook.Sheets(3)
    WrkBook.Sheets("AnotherSheetName").Copy After:=NewBook.Sheets(3)

    NewBook.Sheets(1).Delete
    NewBook.Sheets(1).Delete
    NewBook.Sheets(1).Delete

    NewBook.SaveAs Filename:=Destination & "flujo_" & WrkBook.Name
    NewBook.Close False
    WrkBook.Close False
Loop

app.DisplayAlerts = True

app.Quit
Set app = Nothing
End Sub

Is there a way I could make it work faster?

-Edit- The script takes more or less 3 - 6 seconds per file. That's not too much but I feel it could be much faster. Or is this the fastest I can expect to get with VBA?


texts:
Problem Statement

  You will be given a list of 32 bits unsigned integers. You are required to output the list of the unsigned integers you get by flipping bits in its binary representation (i.e. unset bits must be set, and set bits must be unset).

Input Format

  The first line of the input contains the list size T, which is followed by T lines, each line having an integer from the list.

Constraints

  \$1≤T≤100\$

  \$0≤integer<2^{32}\$

Output Format

  Output one line per element from the list with the requested result.

Solution

for _ in range(int(raw_input())):
    N = int(raw_input())
    N = N & 0xffffffff # 32 bit representation
    print N ^ 0xffffffff

Hint: https://stackoverflow.com/a/16745422/4260745


texts:
So I decided to write my own DI container for educational purposes and would like some feedback on how I can improve the quality of my code.

I'm not sure about the documentation as most of my experience has been with closed source personal code, so I would like some feedback on that.

Another area is where I am using exit(), maybe an exception would be better? Although my experience is minimal here, maybe Exception or RuntimeException?

I would also prefer responses about common good practices over personal preferences.

<?php declare (strict_types = 1);

namespace Rosa;

use RuntimeException;

class Rosa {
    private $objects = [];

    /**
     * Register an instantiated object to the container.
     *
     * @param object $object
     */
    public function register(object $object) : void {
        $this->objects[get_class($object)] = $object;
    }

    /**
     * Fetch a cached object from the container.
     *
     * @param string $objectName
     * @return object
     */
    public function fetch(string $objectName) : object {
        if (array_key_exists($objectName, $this->objects)) {
            return $this->objects[$objectName];
        }

        return $this->make($objectName);
    }

    /**
     * Creates an object from its name and auto-wires constructor arguments.
     *
     * @param string $objectName
     * @return object
     * @throws \ReflectionException
     */
    private function make(string $objectName) : object {
        $reflection = new \ReflectionClass($objectName);

        if (!$reflection->isInstantiable()) {
            exit($reflection->getName() . ' can\'t be instantiated.');
        }

        $arguments = $this->resolveArguments($reflection);

        if (count($arguments) < 1) {
            return $reflection->newInstance();
        }
        else {
            return $reflection->newInstanceArgs($arguments);
        }
    }

    /**
     * Creates an array of arguments from a reflection class.
     * Uses default value if there is one, auto-wires the object if not.
     *
     * @param $reflection
     * @return array
     */
    private function resolveArguments($reflection) : array {
        $constructor = $reflection->getConstructor();
        $parameters = $constructor->getParameters();

        if (!$parameters) {
            return $reflection->newInstance();
        }

        $arguments = [];

        foreach ($parameters as $parameter) {
            if ($parameter->isDefaultValueAvailable()) {
                $arguments[] = $parameter->getDefaultValue();
                continue;
            }

            if ($parameter->getClass() == null) {
                exit($parameter->name . ' on ' . $reflection->getName() . ' needs a default value');
            }

            $arguments[] = $this->fetch($parameter->getClass()->getName());
        }

        return $arguments;
    }
}


texts: Refactor specs for service class methods

texts:
Service Class

# services/search.rb

class Search
  include Rails.application.routes.url_helpers
  include ActionView::Helpers::TagHelper

  def initialize(term, app_ids)
    @term = term
    @app_ids = app_ids
  end

  def results
    term = @term
    app_ids = @app_ids

    multi_search = Tire.multi_search do
      no_app_indices = [Event, PastEvent, Review].map {|c| c.tire.index_name}
      search :without_app, indices: no_app_indices do
        query { string term }
      end

      app_indices = [Question, Answer, Link, ServiceProvider].map {|c| c.tire.index_name}
      search :with_app, indices: indices do
        query do
          filtered do
            query { string term }
            filter :terms, app_id: app_ids
          end
        end
      end
    end
    multi_search.results[:with_app].to_a + multi_search.results[:without_app].to_a
  end

  def autocomplete
    results.map do |result|
      title, caption, route = set_item_based_on_type(result)
      {title: strip_tags(title), label: set_label(strip_tags(title), caption), value: route}
    end
  end

  def strip_tags(title)
    title.gsub(%r{</?[^>]+?>}, '').strip
  end

Specs

describe Search do
  before(:all) do
    Question.index.delete
    Question.tire.create_elasticsearch_index

    @question1 = create :question, content: "Some super question?"
    @question2 = create :question, content: "Some extra question?"

    app = create :app, name: "Marketing", id: 76
    @question1 = create :question, content: "Some super question?", app: app
    @question2 = create :question, content: "Some extra question?", app: app

    # wait for indexing to finish
    sleep 1
  end

  describe "#results" do
    it "returns matched results" do
      Search.new("Some", [76]).results.map(&:content).should == ["Some super question?", "Some extra question?"]
    end

    it "excludes not matching results" do
      Search.new("extra", [76]).results.map(&:content).should == ["Some extra question?"]
    end

    it "returns no matches" do
      Search.new("hiper", [76]).results.map(&:content).should == []
    end

    it "should filter results by app" do
      Search.new("some", [77]).results.map(&:content).should == []
    end
  end

  describe "#autocomplete" do
    it "returns array with matching items" do
      Search.new("super", [76]).autocomplete.should ==
        [{
          :title=>@question1.content,
          :label=>"Some super question? Question",
          :value=>"/Marketing/q/#{@question1.id}"
        }]
    end
  end

  describe "#strip_tags" do
    it "should strip title" do
      Search.new("super", [76]).strip_tags("
Some text
 ").should == "Some text"
    end
  end

Is there a better way to test that methods in service class ?


texts: Changing the first occurrence of a text in a sentence

texts:
The following question was taken from Absolute Java 5th ed. by Walter Savitch:

  Write a program that starts with a line of text and then outputs that line of text with the first occurrence of "hate"  changed to  "love" . For example, a possible sample output might be:
  The line of text to be changed is:
  I hate you.
  I have rephrased that line to read:
  I love you.
   You can assume that the word  "hate"  occurs in the input. If the word  "hate" occurs more than once in the line, your program will replace only the first occurrence of "hate" .  Use     a defined constant for the string to be changed. To make your program work for another string, you should only need to change the definition of this defined constant.

This is the code that I have written:

 public class Question5 {

    private static final String STRING_TO_BE_CHANGED = "hate";

    public static void main(String[] args) {

        System.out.println("The line to be changed is:");
        System.out.println(originalLine());
        System.out.println("I have rephrased that line to read:");
        System.out.println(newLine());
    }

    private static String originalLine() {
        return "I hate you";
    }

    private static String newLine() {
        return originalLine().replaceFirst(STRING_TO_BE_CHANGED, "love");
    }
}


texts: Code to pass json data with WCF REST POST

texts:
I have a WCF REST POST that has JSON data as input,

IService.cs:

 [OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
void ImportJSON(Stream request);

IService.svc:

 public void ImportJSON(Stream request)
    {
        using (var reader = new StreamReader(request))
        {

            var resultStream = reader.ReadToEnd();
            var model = JsonConvert.DeserializeObject<dynamic>(resultStream);
            var resHeaders = model.Headers;
            var resValues = model.Values;
            string str = "";
            string strValues = "";
            foreach (var item in resHeaders)
            {
                str = str + item.Header + ";";
            }
            var stringBuilder = new StringBuilder();
            stringBuilder.AppendLine(str);
            foreach (var item in resValues)
            {
                strValues = item.value + ";";
                stringBuilder.AppendLine(strValues);
                strValues = "";
            }
            System.Guid guid = Guid.NewGuid();
            var path = HttpContext.Current.Server.MapPath("~/App_Data/tmp/" + guid.ToString() + ".csv");
            using (StreamWriter writetext = new StreamWriter(path))
            {
                writetext.WriteLine(stringBuilder);
            }
        }
    }

An exemple of JSON data:

{
    "Headers": [{"Header":"CA"},{"Header":"PE"},{"Header":"AMOUNT"}],
    "Values": [{"value":"toto;tata;titi"}, {"value":"A;2019;S100"}, {"value":"A;2019;S100"}, {"value":"A;2019;S300"},
                {"value":"A;2013;S23"}, {"value":"A;2013;S200"}, {"value":"A;2013;S200"}, {"value":"A;2019;S100"}]
}

In fact, I don't use any classe : I use anonyme data directly, and I use dynamic on the Deserialization JSON,

I have my result as I wish : I get all the data from JSON then I saved all data in a txt/csv  file, My result:

CA;PE;AMOUNT;
toto;tata;titi;
A;2019;S100;
A;2019;S100;
A;2019;S300;
A;2013;S23;
A;2013;S200;
A;2013;S200;
A;2019;S100;

Is my code is correct?

Are there any impact affect performance ?

And is there any problem if I have very long JSON data ?

And if there are any advise or feedback for my code.


texts:
I'm learning SSE for the first time and trying to optimise some code. Using oprofile shows that the CPU usage in this function went down from 2.5% to 0.9% using the code I created. As I've only been reading up on SSE today, I'm sure my code can be improved. Any suggestions?

OProfile shows that time is most spent in:

.20% - _mm_set_ps
.10% - _mm_extract_epi32
.08% - _mm_store_ps
.08% - _mm_add_ps

My attempt at SSE:

void Resample_lerp32_SSE(const ALfloat *data, ALuint frac,
  ALuint increment, ALfloat *RESTRICT OutBuffer, ALuint BufferSize)
{
    ALuint i;
    ALuint pos;
    ALuint pos0_tmp = 0;
    ALuint frac0_tmp = frac;

    ALuint frac0_incr = frac0_tmp + increment;
    ALuint pos1_tmp = frac0_incr>>FRACTIONBITS;
    ALuint frac1_tmp = (frac0_incr & FRACTIONMASK);

    ALuint frac1_incr = frac1_tmp + increment;
    ALuint pos2_tmp = pos1_tmp + (frac1_incr>>FRACTIONBITS);
    ALuint frac2_tmp = (frac1_incr & FRACTIONMASK);

    ALuint frac2_incr = frac2_tmp + increment;
    ALuint pos3_tmp = pos2_tmp + (frac2_incr>>FRACTIONBITS);
    ALuint frac3_tmp = (frac2_incr & FRACTIONMASK);

    __m128i frac4 = _mm_set_epi32(frac3_tmp, frac2_tmp, frac1_tmp, frac0_tmp);
    const __m128i increment4 = _mm_set1_epi32(increment*4);
    const __m128 fracOne4 = _mm_set1_ps(1.0f/FRACTIONONE);
    const __m128i fracMask4 = _mm_set1_epi32(FRACTIONMASK);

    __m128i pos4 = _mm_set_epi32(pos3_tmp, pos2_tmp, pos1_tmp, pos0_tmp);

    for(i = 0;i < BufferSize-3;i += 4)
    {
        __m128 val1 = _mm_set_ps(data[pos3_tmp], data[pos2_tmp], data[pos1_tmp], data[pos0_tmp]);
        __m128 val2 = _mm_set_ps(data[pos3_tmp+1], data[pos2_tmp+1], data[pos1_tmp+1], data[pos0_tmp+1]);

        /* val1 + (val2-val1)*mu */
        const __m128 r0 = _mm_sub_ps(val2, val1);
        const __m128 mu = _mm_mul_ps(_mm_cvtepi32_ps(frac4), fracOne4);
        const __m128 r1 = _mm_mul_ps(mu, r0);
        const __m128 out = _mm_add_ps(val1, r1);

        _mm_store_ps(&OutBuffer[i], out);

        frac4 = _mm_add_epi32(frac4, increment4);
        pos4 = _mm_add_epi32(pos4, _mm_srli_epi32(frac4, FRACTIONBITS));
        frac4 = _mm_and_si128(frac4, fracMask4);

        pos0_tmp = _mm_extract_epi32(pos4, 0);
        pos1_tmp = _mm_extract_epi32(pos4, 1);
        pos2_tmp = _mm_extract_epi32(pos4, 2);
        pos3_tmp = _mm_extract_epi32(pos4, 3);
    }

    pos = pos0_tmp;
    frac = _mm_extract_epi32(frac4, 0);

    for(;i < BufferSize+1;i++)
    {
        OutBuffer[i] = lerp(data[pos], data[pos+1], frac * (1.0f/FRACTIONONE));

        frac += increment;
        pos  += frac>>FRACTIONBITS;
        frac &= FRACTIONMASK;
    }
}

Plain C version:

void Resample_lerp_C(const ALfloat *data, ALuint frac,
  ALuint increment, ALfloat *RESTRICT OutBuffer, ALuint BufferSize)
{
    ALuint pos = 0;
    ALuint i;

    for(i = 0;i < BufferSize+1;i++)
    {
        OutBuffer[i] = lerp32(data + pos, frac);

        frac += increment;
        pos  += frac>>FRACTIONBITS;
        frac &= FRACTIONMASK;
    }
}


texts: Calculating holes on a Tetris grid quickly

texts:
I have created a Tetris AI which can play Tetris on its own given a set of rules. It places the next piece in every possible way on the board, and calculates which position that gives the fewest "holes" on the playfield.

The playfield is represented by an int[] array, where every bit represents a position in a row, and every int represents a row.

A playfield can look like this:

(0000000000000000000000)1111111111
(0000000000000000000000)1111111111
(0000000000000000000000)1111111111
(0000000000000000000000)1111111111
(0000000000000000000000)0111111111
(0000000000000000000000)0111111111
(0000000000000000000000)0111001111
(0000000000000000000000)0111100111

the zeroes in parentheses are not part of the playfield, and are not used. 1 represents an empty square, 0 represents a filled one. So the example above would be a long piece on the left, and a squiggly piece in the middle.

However, to determine if this playfield is "desirable", I calculate the number of holes on the grid. A hole is defined as follows:

An empty square under the topmost filled square in a column.
An empty square in a column next to a column where we have found a filled square, given that the empty square in question is under the topmost filled square in the other column.

I guess it's hard to explain, but I've marked all "holes" here:

(0000000000000000000000)1111111111
(0000000000000000000000)1111111111
(0000000000000000000000)1111111111
(0000000000000000000000)1111111111
(0000000000000000000000)0X11111111
(0000000000000000000000)0X11111111
(0000000000000000000000)0X1X00X111
(0000000000000000000000)0X11D00X11

Every hole is marked with an "X", except for one in the bottom row, since that one is counted twice, because it is under a filled square, and next to a square that is  under a filled square.

Right now this is the optimal solution that I've found. It is a combination of JS1's and Brythan's solutions:

private static int EMPTY_ROW = (1<<xsize)-1;

public int calcHolesConverted(int[] grid) {
    //int gridMask      = (1 << xsize) - 1;
    int underMask     = 0;
    int lneighborMask = 0;
    int rneighborMask = 0;
    int foundHoles    = 0;
    int minY = 0;

    while ( minY < ysize && grid[minY] == EMPTY_ROW ) {
        minY++;
    }

    for (int y = minY; y < ysize; y++) {
        int line   = grid[y];
        int filled = ~line & EMPTY_ROW;

        underMask     |= filled;
        lneighborMask |= (filled << 1);
        rneighborMask |= (filled >> 1);

        foundHoles += setOnes[underMask & line];
        foundHoles += setOnes[lneighborMask & line];
        foundHoles += setOnes[rneighborMask & line];
    }
    return foundHoles;
}

This results in over 10000 Tetris pieces per second, compared to the 4800 that I could accomplish before I asked the question.


texts: Multiple conditions for same table in EF

texts:
I am getting products using given parameters (name of real entity and columns changed for illustration purposes),

    public IQueryable<Product> GetProductsByPara(string price, string weight, string dimensions, string trend)
    {
        var result = dbContext.Products.Where(a =>
            a.Price.ToLower().Equals(price.ToLower()) &&
            a.Weight.ToLower().Equals(weight.ToLower()) &&
            a.Dimensions.ToLower().Equals(dimensions.ToLower()) &&
            a.Trend.ToLower().Equals(trend.ToLower()));
        if (result.Any())
        {
            return result;
        }

        if (!string.IsNullOrWhiteSpace(price))
        {
            result = dbContext.Products.Where(a =>
                a.Price.ToLower().Equals(price.ToLower()) &&
                a.Weight.ToLower().Equals(weight.ToLower()) &&
                a.Trend.ToLower().Equals(trend.ToLower()));
            if (result.Any())
            {
                return result;
            }
        }

        if (!string.IsNullOrEmpty(dimensions))
        {
            result = dbContext.Products.Where(a =>
                a.Dimensions.ToLower().Equals(dimensions.ToLower()) &&
                a.Weight.ToLower().Equals(weight.ToLower()) &&
                a.Trend.ToLower().Equals(trend.ToLower()));
            if (result.Any())
            {
                return result;
            }
        }

        return result;
    }


texts: Repository Pattern universal application

texts:
When I started learning Repository Pattern with Unity few days ago I was under impression that the main benefit of this pattern is the separation of data layer from the business layer.

In other words, if there is a need to change the way, how application stores the data, it's very easy as only one main model takes care of the communication.

This means, that if application currently saves data into a serialized XML files, it would not be very difficult to change this logic to connect to database instead.

I have found few nice demos that are also using Unit Of Work layer, which seemed very handy. Let me show you a bit of the code I have.

public class UnitOfWork : IUnitOfWork
{
    private readonly RepositoryContext _context;
    public IEmployeeRepository Employees { get; set; }

    public UnitOfWork(RepositoryContext context)
    {
        _context = context;
        Employees = new EmployeeRepository(_context);
    }

    public int Complete()
    {
        return _context.SaveChanges();
    }

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

Main Repository Context:

public class RepositoryContext : DbContext
{
    public RepositoryContext() : base("name=RepositoryContext")
    {
    }

    public virtual DbSet<Employee> Employees { get; set; }
    public virtual DbSet<Equipment> Furniture { get; set; }
}

And here is the demo EmployeeRepository:

public class EmployeeRepository:Repository<Employee>, IEmployeeRepository
{
    public EmployeeRepository(RepositoryContext context) : base(context) { }

    public Employee GetEmployeeByName(string sName)
    {
        return MyContext.Employees.FirstOrDefault(n => n.Name == sName);
    }

    public RepositoryContext MyContext
    {
        get { return Context as RepositoryContext; }
    }
}

Employee Repository derives from a generic Repository which looks like this:

public class Repository<T> : Interfaces.Repositories.IRepository<T> where T : class
{
    protected readonly DbContext Context;

    public Repository(DbContext context)
    {
        Context = context;
    }

    public void Add(T item)
    {
        Context.Set<T>().Add(item);
    }

    public IEnumerable<T> Find(Expression<Func<T, bool>> predicate)
    {
        return Context.Set<T>().Where(predicate);
    }

    public T Get(int ID)
    {
        return Context.Set<T>().Find(ID);
    }

    public IEnumerable<T> GetAll()
    {
        return Context.Set<T>().ToList();
    }

    public void Remove(T item)
    {
        Context.Set<T>().Remove(item);
    }
}

Here is the question:

As far as my understanding goes, we are directly declaring, that under our Repository expects in it's constructor DbContext, which is afterwards used under all Add / Remove / Find functions under that particular class.

Currently this model is communicating with the database, but if I wanted (for whatever reason) to change this model to save data in the XML file, I would have to completely rewrite all my Repository classes? Or am I missing something here?

If I am wrong and it is easily doable, could anyone show me how to change the code so that we are serializing values into the XML files, please? I am trying to better understand this Repository Pattern, yet for now it's one big chaos for me.

Any help / suggestions regarding this matter would be highly appreciated.


texts:
I am working on a C# MVC website. in which i am using tabs.I was trying to stay on the current tab when page refreshes.

I achieved this by following code:

$(document).ready(function () {
    if (window.location.href.indexOf("?") > -1) {
        var newURL = location.href;
        window.history.pushState('object', document.title, newURL);
    }
});
$(document).ready(function () {
    $('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
        localStorage.setItem('activeTab', $(e.target).attr('href'));
    });
    var activeTab = localStorage.getItem('activeTab');
    if (activeTab) {
        $('#myTab a[href="' + activeTab + '"]').tab('show');
    }
});

This is working fine. But if the page is load by RedirectToAction from another page then it showing last opened tab, I needed to show the first tab.

So I added a hidden input field in the html.

<input type="hidden" value="@Model.IsRefresh" id="IsRefresh" />

On $(document).ready i change url as follows

$(document).ready(function () {
    if (window.location.href.indexOf("?") > -1) {
        var newURL = location.href.replace("?str=true", "");
        window.history.pushState('object', document.title, newURL);
    }
});

and in GET checks for this bool str and set IsRefresh as false

#region Check Is Page Refresh
if (str != null)
{
    if ((bool)str)
    {
        item.IsRefresh = false;
    }
    else
    {
        item.IsRefresh = true;
    }
}
else
{
    item.IsRefresh = true;
}
str = false;
#endregion

so if IsRefresh is false then it is page refresh and else it is RedirectToAction.

So i changed the code as:

$(document).ready(function () {
    $('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
        localStorage.setItem('activeTab', $(e.target).attr('href'));
    });
    var activeTab = localStorage.getItem('activeTab');

    <!-- added these lines -->
    var refresgh = $("#IsRefresh").val();
    if (!refresgh) {
        activeTab = "";
    }

    if (activeTab) {
        $('#myTab a[href="' + activeTab + '"]').tab('show');
    }
});

Now its working fine, but sometimes i get the feeling that on page refresh different tab is showing. Is something wrong with my code?

Is there any better solution??


texts: String manipulation over 2 tables in database to application

texts:
I have the following function in the database to do string manipulation:

create or replace FUNCTION convert_string
(
    input_string IN VARCHAR2
) RETURN VARCHAR2 AS
output_string VARCHAR(8);
BEGIN
    IF (input_string IS NULL) THEN
        output_string := '';
    ELSIF (NOT (SUBSTR(input_string, 6, 1) >= '0' AND SUBSTR(input_string, 6, 1) <= '9')) THEN
        output_string := '000' || SUBSTR(input_string, 1, 5);
    ELSE
        output_string := '00' || input_string;
    END IF;

    RETURN output_string;
END convert_string;

I'm using the function to perform checking on 2 tables, so my SQL query will be:

SELECT     t1.name
FROM       table1 t1
JOIN       table2 t2 on t1.id = convert_string(t2.id)

But let's say I do not want to create a convert_string function in my database, and would like to do everything on the application side. What is the best way to do it?

The function above can be converted to C# code:

public string ConvertString(input)
{
    if (String.IsNullOrEmpty(input))
        return "";
    else if (!(input[5] >= '0' && input[5] <= '9'))
        return "000" + input.Substring(0,5);
    else
        return "00" + input;
}

Then the SQL query is to be split into 2 database calls:

SELECT     *
FROM       table1

and

SELECT     *
FROM       table2

Those will be returned to their own data tables, and then do a loop or Linq to join these 2 tables. But I wonder whether there is a more efficient / better way to do this.


texts:
Consider the following contrived data type:

Building: int age, char* location, float quality

The location is in the format "XXX-XXX" (exactly 7 characters).

Goal: Serialize the object into a binary format and then deserialize the object to display (on console) the exact same building info as inputed by the user.

For example, suppose the user imputed the building object: age = 45, location = "345-789", quality = "2.3829.

Then the program should display on the console:

age = 45, location = 345-789, quality = 2.3829

Attempt: Although my application works exactly as specified by the goal, I believe there are major inefficiencies in my code. I am asking for feedback directly related to efficiency. Does there exist a more efficient method to accomplish the same goal? This project is for educational purposes and I cannot use any serialization libraries.

#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>

class Building
{
private:
    int m_age; // the age of the building
    char m_locationCode[7]; // location is the format:: example "357-278" (exactly 7 characters)
    float m_buildingQuality; // the quality of the building (scale from 0 - 1000)
    int m_buildingQualityDecimals; // the number of digits after the decimal for building quality
public:
    Building(int age, const std::string& loc, const std::string& quality)
    {
        m_age = age;
        for(unsigned i = 0; i < loc.size(); i++)
            m_locationCode[i] = loc[i];
        char qualityBuffer[10];
        int count = 0;
        bool hitDecimal = false;
        for(int i = 0; i < quality.size(); i++)
        {
            qualityBuffer[i] = quality[i];
            if(quality[i] == '.')
            {
                hitDecimal = true;
            }
            if(hitDecimal == true)
                count++;
        }
        m_buildingQuality = atof(qualityBuffer);
        m_buildingQualityDecimals = count;

    }
    int getAge() {return m_age;}
    std::string getLoc()
    {
        std::string toReturn(m_locationCode, 7);
        return toReturn;

    };
    int getDecimals()
    {
        return m_buildingQualityDecimals;
    }
    float getQuality()
    {
        return m_buildingQuality;
    }
};

int main()
{
    Building b(345, "123-456", "3.23654");

    // Serializing
    std::ofstream file;
    file.open("BinaryBuilding.bin", std::ios::out | std::ios::binary | std::ios::trunc);
    file.write((char*) &b, sizeof(b)); // writing file to binary by casting to a char*
    file.close();

    // Deserialzing
    std::ifstream file2;
    file2.open("BinaryBuilding.bin", std::ios::in | std::ios::binary);
    Building* b2 = new Building(0, "000-000", "0.0");
    file2.read((char *) b2, sizeof(*b2));
    file2.close();

    // Testing process
    std::cout << "Age: " << b2->getAge() << "; Loc: " << b2->getLoc() <<
                "; Building Quality:" <<  std::setprecision(b2->getDecimals()) << b2->getQuality() <<std::endl;

    delete b2;
    return 0;
}

Console Output: Age: 345; Loc: 123-456; Building Quality: 3.23654

Remarks: Notice that I parse the number of characters after the decimal point as inputted by the user. I think this is inefficient since I must store another int inside the class. This is slower and increases the size of the binary file. I want to be able to serialize and deserialize this object as fast as possible. I will eventually extend this to parse millions of objects. My professor told me that the location (i.e. XXX-XXX) should not be written as ASCII. How could the task be accomplished without writing the location to ASCII?


texts:
I'm trying to learn dynamic programming and the most popular one is to find the minimum number of coins for the change. I come up with this but I just want to improve this code which I think it could be shorter in Python but I'm new to Python too.

import sys
coins = [1, 3, 5]
min_coin = [sys.maxint] * 20
min_coin[0] = 0

for min_of_i in range(20):
    for c in coins:
        if c <= min_of_i and (min_coin[min_of_i - c] + 1 < min_coin[min_of_i]):
                min_coin[min_of_i] = min_coin[min_of_i - c] + 1

print min_coin


texts:
api.js

'use strict';
const http = require('http');

module.exports = url => {
  const options = {
    host: url,
    method: 'HEAD',
    path: '/'
  };
  const req = http.request(options);
  req.end();
  const promise = new Promise((resolve, reject) => {
    let connected = false;
    req.on('response', res => {
      connected = res.statusCode < 500;
      resolve(connected);
    });

    req.on('error', err => {
      reject(err);
    });
  });
  return promise;
};

The most confusing part for me is which status codes should be considered a valid candidate? apart from that any comments regarding code are welcome.


texts:
I would really love to hear your critiques on:

Code quality
Code clarity
More efficient alternative code

Code:

function array_mask(array $source, array $filter){
    foreach ($source as $key => $value){
        if (!isset($filter[$key])){
            if (array_search($key, $filter) !== false){
                continue;
            }
            unset($source[$key]);
        } else {
            if (is_array($source[$key])){
                $source[$key] = array_mask($source[$key], $filter[$key]);
            }
        }
    }
    return $source;
}

$source = array(
    'page' => array(
        'q' => 'alkflsdj',
        'x' => 1,
        9   => 'm'
    ),
    'news' => 7
);
$filter = array(
    'page' => array(
        9
    ),
    'news'
);

$result = array_mask($source, $filter);
var_dump($result);

Result:

array
  'page' =>
    array
      9 => string 'm' (length=1)
  'news' => int 7


texts:
My data set is a list of Edges which are passed as a pair of integers. Based on that, I have the following graph implementation for BFS. Could someone please review my code and comment on errors/omissions/efficiency and other points.

#include <queue>
#include <iostream>
#include <vector>

class Graph {

private:
    int num_of_vertices;
    std::vector<int>* Adj;

public:
    Graph(int V){

        this->num_of_vertices = V;
        Adj = new std::vector<int>[V];
    }

    void addEdge(std::vector<std::pair<int, int>* > edge_list)
    {
        for(auto it = edge_list.begin(); it != edge_list.end(); it++) {
            std::pair<int, int>* p = *it;
            Adj[p->first].push_back(p->second);
        }
    }
    void BFS(int start)
    {
        bool* visited = new bool[this->num_of_vertices]();

        for(int i=0;i<num_of_vertices;i++)
            visited[i]=false;

        std::queue<int> queue;
        queue.push(start);
        std::vector<int>::iterator i;

        while(!queue.empty())
        {
            start = queue.front();

            visited[start] = true;
            queue.pop();
            for (i = Adj[start].begin(); i != Adj[start].end(); i++)
            {
                if (!visited[*i])
                    queue.push(*i);
            }
        }

    }

};


texts: Divide and conquer algorithm for max binary gaps

texts:
The codility.com free test is as follows:

  A binary gap within a positive integer N is any maximal sequence of
  consecutive zeros that is surrounded by ones at both ends in the
  binary representation of N.
       For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation
  1000010001 and contains two binary gaps: one of length 4 and one of
  length 3. The number 20 has binary representation 10100 and contains
  one binary gap of length 1. The number 15 has binary representation
  1111 and has no binary gaps.

  Write a function def solution(N) that, given a positive integer N,
  returns the length of its longest binary gap. The function should
  return 0 if N doesn't contain a binary gap.

  For example, given N = 1041 the function should return 5, because N
  has binary representation 10000010001 and so its longest binary gap is
  of length 5.

My implementation is as follows:

def merge_step(x, y, result):

    if x[0] == 1:
        if y[0] == 0 and len(result) == 0:
            result.append(1)

    if x[0] == 0 and y[0] == 0:
        if len(result) > 0:
            result[len(result) -1] = result[len(result) -1] + 1

def divide_and_conquer(array, result):
    # [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1]

    if len(array) == 1:
        return merge_step([array], [array], result)

    mid = len(array) // 2
    x = array[:mid]
    y = array[mid:]

    divide_and_conquer(x, result)
    divide_and_conquer(y, result)
    merge_step(x, y, result)

    if len(result) == 0:
        return 0
    return max(result)

def solution(N):
    # write your code in Python 2.7
    array = [int(x) for x in "{0:b}".format(N)]
    return divide_and_conquer(array, [])

print(solution(1041))
print(solution(15))

The online interpreter says it is correct, but I wanted to check whether there's a better way to do this.

Also, I wanted to verify that my running time is n log(n).  The recursion is \$O(log n)\$ and the max is an \$O(n)\$ operation, correct?


texts: Verifying if a car is a sports car based on speed and horse power

texts:
I have an assignment where I am required to verify if a car is a sports car or not by minimum max speed and minimum horse power. I have finished the program and it works great. I was just wanting to see if you can review my assignment and see if there is room for improvement.

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

namespace Project3
{
class sportsCar
{
    public int _maxSpeed = 0;
    public int _horsepower = 0;
    private static int _MinimumRequiredSpeed = 150;
    private static int _MinimumRequiredHorsepower = 250;

    public bool IsSportsCar()
    {
        if ((_maxSpeed >= _MinimumRequiredSpeed) && (_horsepower >= _MinimumRequiredHorsepower))
            return true;
        else
            return false;
    }
    public void maxSpeed(int newmaxSpeed)
    {
        _maxSpeed = newmaxSpeed;
    }
    public void horsepower(int newhorsepower)
    {
        _horsepower = newhorsepower;
    }
}

class Program
{
    static void Main(string[] args)
    {
        sportsCar car = new sportsCar();

        Console.Write("What is the max speed? ");
        int newmaxSpeed = int.Parse(Console.ReadLine());
        Console.Write("What is the max horsepower? ");
        int newhorsepower = int.Parse(Console.ReadLine());

        car.maxSpeed(newmaxSpeed);
        car.horsepower(newhorsepower);

        bool sportCar = car.IsSportsCar();
        if (sportCar == true)
        {
            Console.WriteLine("This is Definately a Sports Car");
        }
        else
        {
            Console.WriteLine("This is NOT a Sports Car");
        }
    }
}
}


texts:
I want to convert a Version object to a string, but with the parts padded to a given width. E.g. 0.22.1 with parts padded to a width of 2 when converted to string would be "00.22.01"

A simple task, simple enough that I'm surprised it's not part of the class already. I'm not that used to .Net and it's string handling though, could my implementation be more efficient given that I might call it quite often? Or are there already built-in function(s) that might do this for me?

Option Strict On
Option Explicit On

Imports System.Runtime.CompilerServices
Imports System.Text

Module BetterVersion

    <Extension()> Public Function ToString(version As Version, fieldCount As Integer, fieldPadding As Integer) As String
        Dim Builder As StringBuilder = New StringBuilder()
        ' Convert the version to a string and split the result at the version
        ' delimiter (i.e. ".")
        Dim Parts As String() = version.ToString(fieldCount).Split("."c)

        If fieldCount = 0 Then
            Return String.Empty ' No parts so no string
        ElseIf fieldCount = 1 Then
            ' Single part with padding and without trailing delimiter
            Builder.Append(Parts(0).PadLeft(fieldPadding, "0"c))
        Else ' fieldCount >= 2
            For i As Integer = 0 To fieldCount - 2
                ' All but last part with padding and trailing delimiter
                Builder.AppendFormat("{0}.", Parts(i).PadLeft(fieldPadding, "0"c))
            Next
            ' Final part with padding and without trailing delimiter
            Builder.AppendFormat("{0}", Parts(fieldCount - 1).PadLeft(fieldPadding, "0"c))
        End If

        Return Builder.ToString()
    End Function
End Module


texts: Simple Ruby directory navigator functions

texts:
In the process of writing scripts to work with CSVs and other files of the like I found myself in the need of a way to navigate and select files for various purposes. I wrote the following function for one of the scripts I needed to finish quickly and now I'm trying to get it into a more reusable form

def select_file()
  i = 1
  selection_set = Dir.glob("*")
  puts "--------------------------------------------------------------------------"
  puts "Listing entries in #{File.basename(Dir.pwd)}:"
  puts
  selection_set.each do |entry|
    puts i.to_s + " - " + entry
    i = i+1
  end
  print "Select File/Folder: "
  user_selection = gets.chomp
  selection = selection_set[user_selection.to_i - 1]
  puts "Selected: #{selection}"
  puts "--------------------------------------------------------------------------"
  selection
end

In an attempt to make this more reusable in the future I refactored this single function into a series of functions. Part of the motivation in doing it this way was to attempt to use this for displaying other sets of things the user may need to select. Was I better off sticking with the original approach or am I on a decent track but not quite doing it right? I get the sense this can all be done much simpler. Also I am deliberately avoiding using any kind of UI gem for no reason other than I am trying to learn.

def full_directory_navigator
  selection_set = Dir.glob('*', File::FNM_DOTMATCH)
  list_directory_entries(selection_set)
end

def dir_header(pattern)
  100.times { |i| !(i == 99) ? print('-') : puts }
  pattern_message = (pattern == '*') ? '' : "matching \"#{ pattern }\""
  puts
  puts "Listing entries in #{ File.basename(Dir.pwd) }#{ pattern_message }"
  puts
  puts 'Index          Entry'
  100.times { |i| !(i == 99) ? print('-') : puts }
end

def dir_select
  print 'Select File/Folder: '
end

def spacer(i)
  size = i.to_s.size
  spacer = ''
  (9 - size).times { spacer = ' ' + spacer }
  spacer
end

def display_selection_set(selection_set)
  i = 1
  selection_set.each do |entry|
    puts i.to_s + spacer(i) + '-     ' + entry
    i += 1
  end
end

def list_directory_entries(selection_set, pattern = '*')
  dir_header(pattern)
  display_selection_set(selection_set)
  dir_select
  user_selection = gets.chomp.to_i
  selection = selection_set[user_selection - 1]
  puts "Selected: #{selection}"
  selection
end

full_directory_navigator

Any and all comments are appreciated. If my code sucks please let me know so I can start writing less awful code. I also just realized I didn't comment the code at all, so I will begin commenting it and if there are any ambiguous sections it would be greatly appreciated if it could be brought to my attention.


texts:
How would I write a foreach statement that includes both of these statement together

//clear textboxes
foreach (Control c in panel1.Controls.OfType<TextBox>())
        {
            if (!string.IsNullOrEmpty(c.Text))
            {
                c.Text = "";
            }
        }
        //clear price label text
        foreach (Control c in panel1.Controls.OfType<Label>())
        {
            if ((string)c.Tag == "Clearable")
            {
                c.Text = "";
            }
        }


texts: Boggle solver in Rust - Looking for speedup

texts:
I recently made a boggle solver in Rust to compensate for the fact that I'm really bad at boggle. This has also been a good Rust learning experience. The code does what it's supposed to quite well but it is a bit slow, even when compiling with the  -O flag. Since I'm new to Rust, I'm not sure where the slow spots could be. I'm using a hashset to lookup the words, so I assume the lookup isn't the bottleneck. Any tips? (Also, if I'm doing any kind of bad practice, you can let me know). Thanks.

use std::collections::HashSet;
use std::fs;

const MAX_WORD_LEN: usize = 12;

#[derive(Clone, Debug, Copy)]
struct Coordinate {
    row: i64,
    col: i64
}

impl Coordinate {
    // Returns a new coordinate if the move is valid. None otherwise.
    fn move_c(&self, a: i64, b: i64, h: i64, w: i64) -> Option<Coordinate> {
        let h_range = 0..h;
        let w_range = 0..w;
        if h_range.contains(&(self.row + a)) && w_range.contains(&(self.col + b)) {
            Some(Coordinate {row: self.row + a, col: self.col + b})
        }
        else {
            None
        }
    }
}

impl PartialEq for Coordinate {
    fn eq(&self, other: &Self) -> bool {
        self.row == other.row && self.col == other.col
    }
}

fn boggle_solve(grid: &Vec<Vec<char>>, dict: &HashSet<String>) {
    for (i, row) in grid.iter().enumerate() {
        for (j, ch) in row.iter().enumerate() {
            boggle_solve_help(grid, dict, ch.to_string(), Coordinate{row: i as i64, col: j as i64}, vec![Coordinate{row: i as i64, col: j as i64}])
        }
    }

}

fn boggle_solve_help(grid: &Vec<Vec<char>>, dict: &HashSet<String>, word: String, c: Coordinate, path: Vec<Coordinate>) {
    // Base case.
    // No more work if the string is long enough
    if word.len() > MAX_WORD_LEN {
        return;
    }

    if word.len() > 3 && dict.contains(&word) {
        println!("{}", word);
    }

    // For every possible direction the path can take, if it is valid, take it.
    for a in -1..=1 {
        for b in -1..=1 {
           match c.move_c(a, b, grid.len() as i64, grid[0].len() as i64) {

                Some(new_c) if !path.contains(&new_c) => {
                    let mut new_path = path.clone();
                    new_path.push(new_c);
                    let new_word = format!("{}{}", &word, &grid[new_c.row as usize][new_c.col as usize]);

                    boggle_solve_help(grid, dict, new_word, new_c, new_path);
                },

                Some(_) => (),

                None => ()

           }
        }
    }
}

fn main() {
    let contents = fs::read_to_string("words_alpha.txt").unwrap();
    let dict: HashSet<String> = contents.split_whitespace().map(|s| s.to_string()).collect();

    let grid: Vec<Vec<char>> = vec![
        vec!['c', 's', 't', 'e', 't'],
        vec!['a', 'i', 'r', 'l', 's'],
        vec!['p', 'd', 'a', 'e', 's'],
        vec!['u', 'e', 'c', 's', 'e'],
        vec!['r', 'o', 't', 'r', 'i']
    ];

    boggle_solve(&grid, &dict)

}


texts:
I have managed to write some pretty terrible code in VBA and I know there has to be a better way. I have made all of these variables to store some data which I eventually reference in the application.  I'm fairly certain I need to loop over the recordset or fields and store the variables that way but I can't figure out how to do it in a way that actually simplifies this code.  It's torturing me because it seems like a painfully simple concept.

The columns of the table that it is gathering data from looks similar to this:

[LANGUAGE_ID]-[NEXT]-[PREVIOUS]-[RESUME] -- and so on

sqlstmt = "SELECT *" & _
" FROM cf_Language" & _
" WHERE LANGUAGE_ID = " & parm_language & ";"

Set rst_t = dbs.OpenRecordset(sqlstmt, dbOpenSnapshot)

If (parm_language <> 1) Then
    parm_surveyname = UnicodeToAscii(parm_surveyname, True)
    aNext = UnicodeToAscii(rst_t![Next], True)
    aPrevious = UnicodeToAscii(rst_t![previous], True)
    aResume = UnicodeToAscii(rst_t![resume], True)
    aFinish = UnicodeToAscii(rst_t![finish], True)
    aSave = UnicodeToAscii(rst_t![Save], True)
    aLogIn = UnicodeToAscii(rst_t![log_in], True)
    aComplete = UnicodeToAscii(rst_t![complete], True)
    aHeader = UnicodeToAscii(rst_t![header], True)
    aThanks = UnicodeToAscii(rst_t![thanks], True)
    aSavedMsg = UnicodeToAscii(rst_t![saved_msg], True)
    aBlankCode = UnicodeToAscii(rst_t![blank_code], True)
    aInvalidCode = UnicodeToAscii(rst_t![invalid_code], True)
    aTimeOut = UnicodeToAscii(rst_t![timeout], True)
    aClosed = UnicodeToAscii(rst_t![closed], True)
    aAccessCode = UnicodeToAscii(rst_t![access_code], True)
    aConFirstTime = UnicodeToAscii(rst_t![con_first_time], True)
    aAnonFirstTime = UnicodeToAscii(rst_t![anon_first_time], True)
    aAnonResume = UnicodeToAscii(rst_t![anon_resume], True)
Else
    aNext = rst_t![Next]
    aPrevious = rst_t![previous]
    aResume = rst_t![resume]
    aFinish = rst_t![finish]
    aSave = rst_t![Save]
    aLogIn = rst_t![log_in]
    aComplete = rst_t![complete]
    aHeader = rst_t![header]
    aThanks = rst_t![thanks]
    aSavedMsg = rst_t![saved_msg]
    aBlankCode = rst_t![blank_code]
    aInvalidCode = rst_t![invalid_code]
    aTimeOut = rst_t![timeout]
    aClosed = rst_t![closed]
    aAccessCode = rst_t![access_code]
    aConFirstTime = rst_t![con_first_time]
    aAnonFirstTime = rst_t![anon_first_time]
    aAnonResume = rst_t![anon_resume]
End If


texts: What's the right granularity for test-driven development?

texts:
I'm not very experienced in test-driven development (TDD), but I'm trying to get into the groove.  Here I am making a console app that creates records in a database. I bootstrapped by creating a console app and then let MSTest make a unit test for Main(string [] args).

I know I'm doing at least something right, because the tests didn't pass until I did the development -- they "drove" me to "develop".

But I feel like maybe I'm still missing the point, as I didn't really test my code - I tested the database the code acted on.  How would an experienced TDDer approach this?

[TestClass]
public class ProgramTest
{
    private MyEntities _model;

    [TestInitialize()]
    public void MyTestInitialize()
    {
        _model = new MyEntities();
    }

    [TestCleanup()]
    public void MyTestCleanup()
    {
        _model.Dispose();
    }

    [TestMethod()]
    public void MainTest_01_Create_PayTerms()
    {
        string[] args = new[]  { "/Operation", "Insert", "/RecordType", "PayTerms" };
        DirectAgentsService.Program.Main(args);

        _model.PayTerms.SelectValue<string>("it.Name").ShouldContain("Biweekly", "Retainer", "Net 7", "Net 15", "Net 30");
    }
}
static public class Extensions
{
    static public void ShouldContain(this string[] source, params string[] targets)
    {
        foreach (var target in targets)
        {
            Assert.IsTrue(targets.Any(c => c == target), "{0} is missing from collection", target);
        }
    }

    static public void ShouldContain<T>(this T source, params string[] targets) where T : ObjectQuery<string>
    {
        source.ToArray().ShouldContain(targets);
    }
}


texts: Implementing a binary tree in C++ using "std::unique_ptr"

texts:
I have implemented a simple binary search tree class in C++ using std::unique_ptr objects to hold the pointers to each node. In doing this I have come across a situation that is somewhat questionable in the Delete method. Since I can't copy the unique pointers, but I need a way to traverse the tree with a "temporary" pointer, I had to resort to using a raw pointer to do the traversal.

This is the section I am talking about (In the Delete method):

// Need to use a raw pointer because I can't assign to a std::unique_ptr
Node* n = node.get();
while (n->right) {

  // Using a reference to a unique_ptr instead of a raw pointer will cause this line to fail to compile
  n = n->right.get();
}

Is this an acceptable thing to do?

It compiles and runs. And since the underlying pointer is still managed by a unique_ptr object it will be deleted properly. Everything about this works fine, but it just doesn't feel right for some reason.

The full source code is shown below (Feel free to comment on anything else that may be improved as well):

#include <iostream>
#include <memory>

using std::make_unique;
using std::unique_ptr;

template <typename T>
class Tree {

  struct Node {
    Node(const T& value)
      : value(value), left(nullptr), right(nullptr) {}

    T value;
    unique_ptr<Node> left;
    unique_ptr<Node> right;
  };

public:
  Tree() : root_(nullptr) {}

  // Insert a value into the tree
  void Insert(const T& value) {
    Insert(root_, value);
  }

  // Delete a value from the tree
  bool Delete(const T& value) {
    return Delete(root_, value);
  }

  // Search the tree for a node and return true if it is found
  bool Contains(const T& value) const {
    return Contains(root_, value);
  }

private:
  void Insert(unique_ptr<Node>& node, const T& value) {
    if (not node) {
      node = make_unique<Node>(value);
    }
    else {
      value < node->value
        ? Insert(node->left, value)
        : Insert(node->right, value);
    }
  }

  bool Delete(unique_ptr<Node>& node, const T& value) {
    if (not node) {
      return false;
    }
    else if (value == node->value) {
      if (node->left) {
        unique_ptr<Node>& right = node->right;
        node = move(node->left);
        if (right) {

          // Need to use a raw pointer because I can't assign to a std::unique_ptr
          Node* n = node.get();
          while (n->right) {

            // Using a reference to a unique_ptr instead of a raw pointer will cause this line to fail to compile
            n = n->right.get();
          }
          n->right = move(right);
        }
      }
      else {
        node = move(node->right);
      }
      return true;
    }
    else {
      return value < node->value
        ? Delete(node->left, value)
        : Delete(node->right, value);
    }
  }

  bool Contains(const unique_ptr<Node>& node, const T& value) const {
    if (not node) {
      return false;
    }
    else if (node->value == value) {
      return true;
    }
    else {
      return value < node->value
        ? Contains(node->left, value)
        : Contains(node->right, value);
    }
  }

  unique_ptr<Node> root_;
};


texts: Least suprising extension methods for DateTime to NATO date-time group

texts:
I have the following code to get a NATO date-time group for a DateTime. I usually need Zulu-Time or from a specific time zone. Is it clear what those methods are providing? If want to parse a NATO dtg string would those be extension methods for string or DateTime?

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

namespace scratchpad
{
/// <summary>
/// Create NATO date-time group from DateTime
/// </summary>
static class NatoDtg
{
    /// <summary>
    /// Get NATO date-time group for UTC/Zulu timezone
    /// </summary>
    /// <param name="dt">this</param>
    /// <returns>NATO date-time group</returns>
    public static string ToZuluDtg(this DateTime dt)
    {
        DateTime utc = dt.ToUniversalTime();
        CultureInfo ci = new CultureInfo("en-GB");

        StringBuilder builder = new StringBuilder();
        builder.Append(utc.ToString("ddHHmm", ci));             // day, hours, minutes
        builder.Append("Z");                                    // time zone
        builder.Append(utc.ToString("MMMyy", ci).ToLower());    // month, year
        return builder.ToString();
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="dt">this</param>
    /// <param name="tz">Time zone for the </param>
    /// <returns></returns>
    public static string ToDtg(this DateTime dt, TimeZoneInfo tz)
    {
        if (tz == null) throw new ArgumentNullException("TimeZoneInfo is null");
        CultureInfo ci = new CultureInfo("en-GB");
        StringBuilder builder = new StringBuilder();
        builder.Append(dt.ToString("ddHHmm", ci));

        TimeSpan ts = tz.GetUtcOffset(dt);

        char letter = '#';
        if(ts.Hours == 0)
        {
            letter = 'Z';
        }
        else if(ts.Hours >= 1 && ts.Hours <= 9) // A-I
        {
            letter = 'A';
            letter += (char)(ts.Hours-1);
        }
        else if(ts.Hours >= 10 && ts.Hours <= 12) // K-M TRICKY: skip J (Juliet)
        {
            letter = 'A';
            letter += (char)ts.Hours;
        }
        else if(ts.Hours >= -12 && ts.Hours <= -1) // N-Y
        {
            letter = 'Z';
            letter += (char)ts.Hours;
        }
        else
        {
            throw new InvalidOperationException("Unknown UTC offset for timezone");
        }

        builder.Append(letter);
        builder.Append(dt.ToString("MMMyy", ci).ToLower());
        return builder.ToString();
    }
}

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

        DateTime now = DateTime.Now;

        Console.WriteLine("Zulu   DTG {0}", now.ToZuluDtg());
        Console.WriteLine("Berlin DTG {0}", now.ToDtg(TimeZoneInfo.GetSystemTimeZones().Where(i => i.DisplayName.Contains("Berlin")).FirstOrDefault()));
        Console.WriteLine("Local  DTG {0}", now.ToDtg(TimeZoneInfo.Local));
        Console.ReadLine();
    }
}
}


texts: Codeigniter calling conditional data retrieval model method from controller

texts:
I am wondering if there's a better way to structure my code. I want to keep my controllers thin but at the same time want to keep the model methods flexible. As you can see below, it's almost as if I can write active record code directly on my controller itself (Which not be a good thing?)

The line of code in the controller:

$request_forms = $this->request_form_model->where('status', Request_form_model::STATUS_ON)->find_all(NULL, NULL, NULL, ['title', 'id', 'service_category_id'])->result();

The relevant code in MY_Model which the Request_form_model extends from:

function where($field, $value){
    $this->db->where($field, $value);
    return $this;
}

function find_all($limit = NULL, $offset = NULL, $order_by = NULL, $select_fields = '*', $escape_select = NULL){

    if( is_array( $select_fields ) ) {
        $select_fields = implode(',', $select_fields);
    }

    $this->db->select($select_fields, $escape_select);

    if(isset($order_by)) {
        $this->order_by($order_by);
    }

    $this->limit($limit, $offset);

    return $this->db->get_where($this->table_name);
}


texts: Function to get the next character of a giving position of strings of a dataframe

texts:
I want to get the next character giving a position of a another character of a string in a dataframe. If we have browsed every character of a string I should go to the next line.

And to do so I have written the function bellow.

def get_char(df, y, z):
    if z < len(df[0][y])-1:
        return df[0][y][z+1]
    elif z == len(df[0][y])-1:
        if y < len(df[0])-1:
            return df[0][y+1][0]

so for the dataframe :

ar = np.array(["aba", "bcb", "zab"])
df = pd.DataFrame(ar)

if I

print get_char(df, 1, 2)

gives me z

and

print get_char(df, 2, 2)

should return nothing , in my function it returns None

I am pretty sure that I can do it with a much easier way.

My dataframe will have only one column.


texts:
This function replaces some XML tag values. The tags appear in the XML exactly once.I want to know if this can be done in a better way.

sub editConnConfig{
my ($DOMAIN,$rscDir,$walletDir,$DEFAULTPORT)=@_;
`perl -pi -e 's!<trustStore>.*?</trustStore>!<trustStore>$walletDir/fctrust.jks</trustStore>!sg' "$rscDir/ConnectionConfig.xml" 2>&1`;
`perl -pi -e 's!<keyStore>.*?</keyStore>!<keyStore>$walletDir/fckey.jks</keyStore>!sg' "$rscDir/ConnectionConfig.xml"`;
`perl -pi -e 's!<keyStorePassword>.*?</keyStorePassword>!<keyStorePassword>jkspass1</keyStorePassword>!sg' "$rscDir/ConnectionConfig.xml"`;
`perl -pi -e 's!<directoryName>.*?</directoryName>!<directoryName>$DOMAIN</directoryName>!sg' "$rscDir/ConnectionConfig.xml"`;
`perl -pi -e 's!<dbDaemonPort>.*?</dbDaemonPort>!<dbDaemonPort>$DEFAULTPORT</dbDaemonPort>!sg' "$rscDir/ConnectionConfig.xml"`;
}


texts:
I was doing Search in sorted array question from leetcode
Question
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
My solution
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var search = function(nums, target) {
    for (let i=0; i<nums.length; i++) {
        if (target === nums[i]) return i
    }
    return -1
};

While this algo works, I am not sure if this is optimal or correct? for question with medium difficulty. Can someone verify it?


texts: Fetching the website version number from the database

texts:
I was just writing some code the other day, and I found myself writing something I am not sure whether it is OK to do it like this, or not.

Let me give an example of what this is:

I have this Method:

    public static string STOLENVersion()
    {
        string version = string.Empty;
        try
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("SELECT TOP 1");
            sb.AppendLine("    [WebsiteVersion]");
            sb.AppendLine("FROM [WebsiteDefaults]");
            using (SqlCommand cmd = new SqlCommand(sb.ToString(), NewSQLConnection))
            {
                cmd.Connection.Open();
                version = cmd.ExecuteScalar().ToString();

                cmd.Connection.Dispose();
            }
        }
        catch (Exception)
        {
            throw;
        }
        return "Version: " + version;
    }

And I have this property:

public static SqlConnection NewSQLConnection
    {
        get
        {
            return new SqlConnection(ConfigurationManager.ConnectionStrings["DebugDB"].ConnectionString);
        }
    }

I am disposing the SqlCommand's connection inside its using block, and this method can be called multiple times (maybe like 10 times every minute, as users log on to the website, as an example)