texts:
I've got a jQuery/JavaScript script for a menu that uses icons as well as label text. When the icon or text is clicked, it turns blue, until such time as another icon is clicked.
Also, the page scrolls down to the relevant div on the page, but the menu bar still stays fixed along the top of the screen.

I've created several versions of this script and this is the most efficient (least code) I have managed so far.

Can anyone tell me any methods to use instead, or any other way I could make it more efficient?

window.onload = function() {

        [].forEach.call(document.querySelectorAll('.navico'), function(el) {
        el.addEventListener('click', imageButtonClickHandler);
    });

        function imageButtonClickHandler()
        {
                switch(this.id)
                {
                        case "aboutnav":
                                grey();
                                $('#abouttitle').css('color', 'blue');
                                $('#a').css('color', 'blue');
                                $('html, body').animate( { scrollTop: $("#about").offset().top - 90 }, 2000);
                        break;
                        case "routenav":
                                grey();
                                $('#routetitle').css('color', 'blue');
                                $('#b').css('color', 'blue');
                                $('html, body').animate( { scrollTop: $("#route").offset().top - 90 }, 2000);
                        break;
                        case "enternav":
                                grey();
                                $('#entertitle').css('color', 'blue');
                                $('#c').css('color', 'blue');
                                $('html, body').animate( { scrollTop: $("#enter").offset().top - 90 }, 2000);
                        break;
                        case "racedaynav":
                                grey();
                                $('#racedaytitle').css('color', 'blue');
                                $('#d').css('color', 'blue');
                                $('html, body').animate( { scrollTop: $("#raceday").offset().top - 90 }, 2000);
                        break;
                        case "gallerynav":
                                grey();
                                $('#gallerytitle').css('color', 'blue');
                                $('#e').css('color', 'blue');
                                $('html, body').animate( { scrollTop: $("#gallery").offset().top - 90 }, 2000);
                        break;
                        case "newsnav":
                                grey();
                                $('#newstitle').css('color', 'blue');
                                $('#f').css('color', 'blue');
                                $('html, body').animate( { scrollTop: $("#news").offset().top - 90 }, 2000);
                        break;
                        case "resultsnav":
                                grey();
                                $('#resultstitle').css('color', 'blue');
                                $('#g').css('color', 'blue');
                                $('html, body').animate( { scrollTop: $("#resu").offset().top - 90 }, 2000);
                        break;
                        case "contactnav":
                                grey();
                                $('#contacttitle').css('color', 'blue');
                                $('#h').css('color', 'blue');
                                $('html, body').animate( { scrollTop: $("#contact").offset().top - 90 }, 2000);
                        break;

                }
        }
};

function grey()
        {
                $('.sectitle').css('color', 'grey');
                $('.roger').css('color', 'grey');
                return;
}


texts:
I do a lot of PC swaps/replacements for my role. I've decided to write a script to assist with backing up the user's profile and network drives.

I'd like to see how my script stands now. I'm still working to implement more features such as backing up saved wireless networks and printers.

#get current user's ID
$userID=$env:UserName

#####################################
### Backup user's saved documents ###
#####################################

$FoldersToCopy = @(
    'Desktop'
    'Downloads'
    'Favorites'
    'Documents'
    'Pictures'
    'Videos'
    'AppData'
    )

$SourceRoot      = "C:\Users\$User"
$DestinationRoot = "$PSScriptRoot\fileBackup\$userID\"

foreach( $Folder in $FoldersToCopy ){
    $Source      = Join-Path -Path $SourceRoot -ChildPath $Folder
    $Destination = Join-Path -Path $DestinationRoot -ChildPath $Folder

    Robocopy.exe $Source $Destination
    }

#####################################
###  Backup user's mapped drives  ###
#####################################

$mappedDrives = @()
$drives = Get-PSDrive -PSProvider FileSystem

foreach ($drive in $drives) {
    if ($drive.DisplayRoot) {
        $mappedDrives += Select-Object Name,DisplayRoot -InputObject $drive
    }
}

New-Item -ItemType Directory -Force -Path $PSScriptRoot\fileBackup\$userID\mappedDrives
$mappedDrives | Export-Csv $PSScriptRoot\fileBackup\$userID\mappedDrives\mappedDrives.csv


texts: Optimizing a nested for loop over JS array of objects

texts:
NOTE: I'm bringing this question up in code review rather than stack overflow since I already have a working solution. I just am looking for ways to do it better.

I have two arrays. One is an array of simple strings (i.e. A1), while the other is an array of objects (i.e. A2). I need to pluck only those objects from A2, that  have relevant keys present in A1.

Here is my implementation using a double for loop. It works, but is not elegant or efficient, I feel. How do I make this run better? Use of ext libraries such as underscore JS is allowed.

var A1  = ["1","2","3","4"];

var A2 = [
    {label:"one", value:"1"},
    {label:"two", value:"2"},
    {label:"three", value:"3"},
    {label:"four", value:"4"},
    {label:"five", value:"5"},
    {label:"six", value:"6"},
];

       var result = [];

       for(var i=0; i<A2.length; i++){
           for(var j=0; j<A1.length; j++ ){
               if(A1[i] == A2[j].value){
                   result.push( A2[j]);
               }
           }
       }

The output of the above is :

result = [
    {label:"one", value:"1"},
    {label:"two", value:"2"},
    {label:"three", value:"3"},
    {label:"four", value:"4"},
]


texts: Click and/or focus outside & -webkit-tap-highlight-color

texts:
I'm working code sample here.

Note: Above only tested in Firefox 13.0.1, iPad (non-retina) and Chrome 20.0.x.

Here's the relevant code:

var $outside = $(document)
    .add($('html'))
    .add($(':not[' + data.target + ']'));

$outside.on('focusin.goober click.goober', function(e) {

    if ($(e.target).closest(data.target).length === 0) {

        $outside.off('.goober');

        data.divs.hide(); // Collection of sub menu divs.

    } else {

        return true;

    }

}).css('-webkit-tap-highlight-color', 'rgba(0, 0, 0, 0)'); // Hide tap highlight color via Mobile Safari.

I'm looking for feedback on two issues:

Clicking and/or focusing outside: Where you see

var $outside = $(document).add($('html')).add($(':not[' + data.target + ']'));

that's where I check for focusin/click events outside the target menu. I have my reservations about applying event handlers to everything just to detect an outside focus/click. Without using a plugin, is there a better way to detect focus/click outside of a target element? Could this code be improved?
I'm also concerned about how -webkit-tap-highlight-color behaves when tapping outside via iPad. As a quick monkey patch, I've added

.css('-webkit-tap-highlight-color', 'rgba(0, 0, 0, 0)')

but I don't yet see that as the perfect solution.

In regards to #2 above:

I wonder if I should add a CSS class to the <html> element, something like "disable-highlight", and have in my CSS

.disable-highlight * { -webkit-tap-highlight-color: rgba(0, 0, 0, 0); }

and have JS add the class when the menu is being interacted with (and remove it when its not)? I rarely use * selector in my CSS these days, but as a temporary way to hide the tap/click highlight, maybe that's not a bad idea?


texts:
I am going in a circle over and over trying to write a "supermarket" application using OOP.

The app should be useful for the employees of a supermarket. The app reads data from a CSV file which looks like this:

name,amount
soap,4
rice,5
bread,10

The supermarket has cashiers and managers. Cashiers should only be able to view the amount for a product. Managers can view but also change an amount.

Here's the code I came up with:

import pandas

class Data:
    """Creates a pandas dataframe out of a text file"""
    def __init__(self, datafile = "products.txt"):
        self.datafile = datafile

    def get_dataframe(self):
        df = pandas.read_csv("products.txt", index_col = "name")
        return df

    def save_to_csv(self):
        df = pandas.read_csv("products.txt", index_col = "name")
        df.to_csv(self.datafile)
        print(df)

class Product:
    """Represent a product from the dataframe table"""

    def __init__(self, name, dataframe = Data().get_dataframe()):
        self.name = name
        self.dataframe = dataframe

    def get_amount(self):
        """Return the available amount of the product object taken from the dataframe"""
        return self.dataframe.loc[self.name, "amount"]

    def add_amount(self, amount, password):
        """Changes the dataframe by adding an amount to the existing amount"""
        if password == 1234:
            self.dataframe.loc[self.name, "amount"] += amount
            data = Data()
            data.save_to_csv()
            print("Saved")
        else:
            return "You're not a manager"

    def remove_component(self, person):
        """Changes the dataframe by removing an amount from the existing amount"""
        if password == 1234:
            self.dataframe.loc[self.name, amount] -= 1
        else:
            return "You're not a manager"

    def __del__(self):
        """Delete the dataframe from memory when Product is destroyed"""
        del self.dataframe
        Data().save_to_csv()

I think the authentication layer is very poorly implemented here. I simply added a conditional in the add and remove methods. Is there any better way to do the authentication part?

Should I also create Manager and Cashier classes in case I expand the program later. For example, adding info about salaries for managers and cashiers. That would require to have Manager and Cashier objects I guess.

Will the code load many Data objects? Should I use a singleton for the Data object?

What other design pattern could I have used for this app?


texts:
In this question here on S.O, the accepted answer suggests to use both anonymous function and factory pattern for dealing with PDO connection. I believe the anonymous function is used in case a connection to a different database needs to be established, a different function will be defined for that. In that case, will it be alright to move the anonymous function to the factory class itself? With this approach  just passing the PDO parameters to the constructor will achieve the same as the original answer.

Something like:

class StructureFactory
{
    protected $provider = null;
    protected $connection = null;

    public function __construct( $PDO_Params )
    {
        $this->provider = function() {
            $instance = new PDO($PDO_Params["dsn"], $PDO_Params["username"], $PDO_Params["password"]);
            $instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            return $instance;
        };
    }

    public function create( $name)
    {
        if ( $this->connection === null )
        {
            $this->connection = call_user_func( $this->provider );
        }
        return new $name( $this->connection );
    }

}


texts: Customer ViewModel with optional JSON initialization parameter

texts:
I have a situation where I have a ViewModel:

// Main_ViewModel

function MainViewModel()
{
     var self = this;
     this.customerList = ko.observableArray(GetCustomersFromServer());
}

// BIND VIEWMODEL

ko.applyBindings(new MainViewModel());

// GET CUSTOMERS FROM SERVER

function GetCustomersFromServer (){

  var customers = [];
  $.ajax({
        //.....other options...
        success: function(response){

        for(var i =0; i < response.length; i++){
             customers.push(new Customer(response[i]));
         }
    }
   });
  return customers;
}

// HTML:

     Customer Name
      <input type='text' class="form-control" data-bind="value: CustomerName" />

// CUSTOMER VIEW MODEL

function Customer(customer) {
    var self = this;

    if (customer === undefined || customer === null) {
        self.CustomerId = ko.observable();
        self.CustomerName = ko.observable();
        self.DateOfBirth = ko.observable(new Date());
        self.EmailAddress = ko.observable();

        self.CustomerContacts = ko.observableArray();
    }
    else {
        self.CustomerId = ko.observable(customer.CustomerId);
        self.CustomerName = ko.observable(customer.CustomerName);
        self.DateOfBirth = ko.observable(customer.DateOfBirth);
        self.EmailAddress = ko.observable(customer.EmailAddress);

        self.CustomerContacts = ko.mapping.fromJS(customer.CustomerContacts, customMapping);

    }
}

There are two ways to declare ViewModel:

var customer = new Customer(); will be used to create a new Customer. This will add a new customer.
var customer1 = new Customer(customerParameter); is used to update an existing customer. Customer Object is returned from server (JSON format) and assigned to the viewModel.

Is there a cleaner way to define this ViewModel?

Like in C#, we have multiple constructors:

public class Customer
{

    public int CustomerId {get;set;}
    public DateTime DateOfBirth {get;set;}

    public Customer(int customerId): this()
    {
        CustomerId = customerId;
    }

    public Customer()
    {
        DateOfBirth = DateTime.Now;
    }
}

Is there something similar I can do in JavaScript - KnockoutJS?


texts: Calculator of combinations without repetition

texts:
I am interested to find an absolute value (not an approximation) of "combination without repetition" for given \$n\$ and \$k\$, or \$\binom{n}{k}\$.

The brute force solution would look like this

private static ulong Factorial(int x)
{
    ulong res = 1;
    while (x > 1)
    {
        res *= (ulong)x--;
    }
    return res;
}

public static int Combination0(int k, int n)
{
    k = Math.Min(k, n - k);
    if (n < 2 || k < 1) return 1;
    if (k == 1) return n;
    return (int)(Factorial(n) / (Factorial(k) * Factorial(n - k)));
}

We can slightly optimize this solution, by finding \$\prod_{n\geq i>k}{i}\$
instead of \$\frac{n!}{(n-k)!}\$.

private static ulong Factorial(int x, int until = 0)
{
    ulong res = 1;
    while (x > until)
    {
        res *= (ulong)x--;
    }
    return res;
}

public static int Combination1(int k, int n)
{
    k = Math.Min(k, n - k);
    if (n < 2 || k < 1) return 1;
    if (k == 1) return n;
    return (int)(Factorial(n, n - k) / Factorial(k));
}

But these two solutions have one significant problem - we are limited by ulong.MaxValue, which is more than \$20!\$, but less than \$21!\$.

Another way to find the number of combinations, which doesn't have the previously described problem, is the Pascal's triangle.

public static int Combination2(int k, int n)
{
    k = Math.Min(k, n - k);
    if (n < 2 || k < 1) return 1;
    if (k == 1) return n;
    int[] triangle = new int[k + 1];
    triangle[0] = 1;

    // expanding
    int i = 0;
    for (; i < k; i++)
    {
        for (int j = i + 1; j > 0; j--)
        {
            triangle[j] += triangle[j - 1];
        }
    }

    // progressing
    for (; i < n - k; i++)
    {
        for (int j = k; j > 0; j--)
        {
            triangle[j] += triangle[j - 1];
        }
    }

    // collapsing
    for (; i < n; i++)
    {
        int until = k - (n - i);
        for (int j = k; j > until; j--)
        {
            triangle[j] += triangle[j - 1];
        }
    }
    return triangle[k];
}

But the problem is that Combination2 is significantly slow.

I would appreciate any comments and suggestions for an improvement.

Update

@quasar and @henrik-hansen suggested the way to prevent overflow by calculating \$\prod_{0 \leq i < k}{\frac{n-i}{i+1}}\$.


texts: Cancel Long Running Query using Cancellation Token AND SqlCommand.Cancel()

texts:
I need to be able to cancel a long running query programmatically through our application.  The code below will kick off a long running query and give control back to the main thread.  At any arbitrary time, a user could choose to cancel the query.  It both cancels the Task as well as cancels the query in SQL Server. I can check the status of the query in SQL Server with select * from sys.query_store_runtime_stats to verify that the query was in fact aborted.  This is important as I need to make sure it's not just canceled in the app but in the database as well.

The code below does this, but I'm hung up on the line where I Register the cmd.Cancel method with the cancellationToken, cancellationToken.Register(cmd.Cancel); Is there a potential issue since I'm referencing a variable created inside the scope of the Task.Run from the Main method(outside the Task.Run scope)?

Also, I'm including the cmd.Cancel bit so that the SQL query actually gets cancelled and not just the task that kicked it off.  Is there a better way to ensure that the long running SQL query currently being executed in the database is aborted? (again, the code below does this, just wondering if there is a better solution for cancelling a SQL query from the c# code that initiated the SQL query)

I'm using .NET Core 3.1 preview 3 and SQL Server 2017 with the code posted below.

using Microsoft.Data.SqlClient;
using System;
using System.Threading;
using System.Threading.Tasks;

public class Program
{
    public static void Main(string[] args)
    {
        var tokenSource = new CancellationTokenSource();
        var cancellationToken = tokenSource.Token;

        Task.Run(async () =>
        {
            await using var cn = new SqlConnection(CONNECTION_STRING);
            await using var cmd = new SqlCommand(LONG_RUNNING_SQL, cn);
            cancellationToken.Register(cmd.Cancel); // is this bad??
            await cn.OpenAsync(cancellationToken);
            await using var reader = await cmd.ExecuteReaderAsync(cancellationToken);
            while (await reader.ReadAsync())
            {
            }
        }, cancellationToken);

        Console.WriteLine("Press z+<Enter> to Stop");
        while (true)
        {
            if (Console.Read() == 'z')
            {
                tokenSource.Cancel();
                break;
            }

        }
    }

    private const string CONNECTION_STRING = "server=.;database=scratch;trusted_connection=true;";
    private const string LONG_RUNNING_SQL = @"
Declare @start bigint, @end bigint
Select @start=1, @end=999999
;With NumberSequence( Number ) as
(
    Select @start as Number
        union all
    Select Number + 1
        from NumberSequence
        where Number < @end
)
Select * From NumberSequence Option (MaxRecursion 0)
";
}


texts: Password Entropy in Lazarus (Delphi-like)

texts:
My today's goal was to create a function, which would evaluate the entropy of a given string password. It's mostly about how random the password is.

This little code is based on the C# code from Jeff Atwood answer post on Calculating entropy of a string

Based on the wikipedia article I checked this as ok, still I am unsure if the logarithms are ok, or not, but it seems to work.

Let me know, please, if you see any problem with this:

function TPassword.GetEntropy: Extended;

type
  TDictionary = specialize TFPGMap<Char, Integer>;

var
  Dictionary: TDictionary;
  I: Integer;
  Chr: Char;
  PasswordLength: Integer;
  Frequency: Extended;

begin

  // dictionary initialization
  Dictionary := TDictionary.Create;

  try

    // in this cycle we add distinct keys into mapped dictionary with value 1
    // if the key (char) is already there, we increase the value
    for I := 1 to Length(FPassword) do begin

      Chr := FPassword[I];

      if Dictionary.IndexOf(Chr) = -1
        then Dictionary.Add(Chr, 1)
        else Dictionary[Chr] := Dictionary[Chr] + 1;

    end;

    // now that we went through the string and mapped its content,
    // we have for password 'abbbgg' map like a=>1, b=>3, g=>2

    PasswordLength := Length(FPassword);

    Result := 0;

    Frequency := 0;

    // - in this cycle we go through each dictionary item
    // - first we take the number of its occurrences in the string
    // and divide it with password length, let's call it frequency
    // - then there is the main part where we multiply the frequency
    // with natural logarithm of frequency divided by natural logarithm of 2
    // and we are adding it to the result until we went through all keys

    for I := 0 to Dictionary.Count - 1 do begin

      Frequency := Dictionary.Data[I] / PasswordLength;

      Result := Result - (Frequency * (Ln(Frequency) / Ln(2)));

    end;

  finally

    // dictionary freeing
    Dictionary.Free;

  end;

end;


texts: Finding all simple (without internal cycles) paths in a directed graph with total >1.0 weight

texts:
Assume directed graph with each edge being weighted by some positive float.

  Problem: find all simple paths (in other words, [0, 1, 2, 0] is
  simple while [0, 1, 0, 1, 2, 0] is not due to internal [0, 1, 0]
  cycle) with length <= cutoff and "push" them using pusher
  callback.

P.S. There exists some realtime engine (abstracted out by pusher) that does such traversal frequently and algorithm should be optimized to be as fast as possible.

from collections import deque
def algorithm(G, source_node, target_node, pusher, cutoff=5):
    queue = deque([[source_node]] if source_node in G else deque())
    while len(queue):
        path = queue.popleft()
        if len(path) == cutoff:  # no sense to keep this path, it not gonna fit the limit
            continue
        adjacency_nodes = G[path[-1]]  # all the neighbours from the latest node in this path
        if not len(adjacency_nodes):  # deadend reached: you can't get any further from this node and it doesn't fit the requirement, so just forgetting it
            continue
        for adjacency_node in adjacency_nodes:
            extended_path = path.copy() + [adjacency_node]  # might some smart linked list do any better here?
            if adjacency_node == target_node:
                pusher(extended_path)  # wow! found one! does not make sense to keep it, since any other path from here will introduce an internal cycle, right?
            else:
                queue.append(extended_path)  # stay calm and keep trying


texts:
I am looking to increase the speed of this Excel VBA Nested Loop.  The loop compares dates from one sheet to a secondary sheet.  If they match, I change the border around the cell to highlight it.  It currently works fine, but takes about 30 seconds to process per sub. Is there a way to implement an array or other tactic to speed it up?

Sub Single()

Dim DateRng As Range, DateCell As Range, DateRngPay As Range
Dim cellA As Range
Dim cellB As Range
Dim myColor As Variant

Set DateRng = ActiveWorkbook.Worksheets("SS").Range("B11:F16,I11:M16,P11:t16,B19:F24,I19:M24,P19:t24,B27:F32,I27:M32,P27:t32,B35:F40,I35:M40,P35:t40")
Set DateRngPay = ActiveWorkbook.Worksheets("PS").Range("C2:C67")
myColor = Array("38")

If ActiveWorkbook.Worksheets("Info").Range("B67") = 1 Then
    With DateRng
            .Interior.ColorIndex = xlColorIndexNone
            .Borders.ColorIndex = 1
            .Borders.Weight = xlHairline
    For Each cellA In DateRng
        For Each cellB In DateRngPay
                If cellB.Value > "" And cellA.Value > "" And cellB.Value = cellA.Value Then
                With cellA.Borders
                    .ColorIndex = myColor
                    .Weight = xlMedium
                End With
                Exit For
            End If
        Next cellB
    Next cellA
    End With
End If
End Sub


texts: Project Euler 4: Largest palindrome product in Functional Programming

texts:
I wanted to practice functional programming (fp) without using any library but using vanilla JS only. So I took the 4th problem from project euler:

  A palindromic number reads the same both ways. The largest palindrome
  made from the product of two 2-digit numbers is 9009 = 91 × 99.

  Find the largest palindrome made from the product of two 3-digit
  numbers.

My solution in fp looks like this:

/*jshint esversion: 6 */
(function () {
  'use strict';

  function* multiply(factor1, factor2) {
    let palindromeNumbers = 0;

    while (true) {
      const product = factor1 * factor2;
      if (isSymmetric(product) && palindromeNumbers < product) {
        palindromeNumbers = product;
      }
      if (factor1 <= 100) {
        factor1 = 999;
        factor2--;
      } else if (factor2 <= 100) {
        yield true;
        return palindromeNumbers;
      } else {
        factor1--;
      }
    }
  }
  const isEqual = (value, compare) => {
    if (value.length != compare.length) {
      return false;
    }
    if (value.length === 1 && value[0] === compare[0]) {
      return true;
    }
    return value[0] === compare[0] &&
      isEqual(value.slice(1), compare.slice(1));
  };
  const isSymmetric = n => {
    const asArray = n.toString()
      .split('');
    const mid = Math.floor(asArray.length / 2);

    const half1 = asArray.slice(0, mid);
    const half2 = asArray.slice(asArray.length - mid)
      .reverse();
    return isEqual(half1, half2);
  };

  const getAllPalindromeNumbers = multiply(999, 999);

  while (getAllPalindromeNumbers.next()
    .value !== true) {}
  const solution = getAllPalindromeNumbers.next()
    .value;
})();

First I wanted to solve this using recursion. But I reached the stack size pretty quickly. Therefore I opted for generators. But I'm not satisfied with my solution especially because of the multiply generator:

I'm am mutating palindromeNumbers, factor1, and factor2
I'm using a while loop twice

Is it possible to solve this problem yet still be consistent with fp, i.e. no mutations and no loops? And of course: Any other improvement suggestions are welcomed.


texts:
Could I get a review on the following regex:

^import[\s\S&&[^\*\n]]*?([\*]{1}\;\s*$)

All the details:

Years ago a colleague shared a useful little regex for finding wildcard imports in Java, such as the following:

import org.example.project.*;

But not:

import org.example.project.someClass;

The critical bit being the *. Of course, there's a lot of possible variation in the legal whitespace. Spaces or tabs could be inserted pretty much anywhere.

I couldn't find the regex, or the right search-foo to find one online, so had a stab at writing my own. For the record I am not a natural regexer, I'm sure It could be shorter and simpler.

The regex engine is that in Jetbrains' IntelliJ IDEA, which I assume is Java regex.


texts:
I have multiple distinct processes that need to access external resources that are rate limited.  The processes are all async in nature and run in different applications.  In times past I would just use SemaphoreSlim this design doesn't allow for that.

I've found several samples that seem to be half complete, or cut and paste into their code.  This was derived from an existing post, but heavily modified to encompass the additional methods and to honor the cancellation token.

Any feedback would be appreciated.

public sealed class SemaphoreAsync : IDisposable
{
  Semaphore _semaphore;

  private SemaphoreAsync(Semaphore sem) => _semaphore = sem;
  public SemaphoreAsync(int initialCount, int maximumCount) => _semaphore = new Semaphore(initialCount, maximumCount);
  public SemaphoreAsync(int initialCount, int maximumCount, string name) => _semaphore = new Semaphore(initialCount, maximumCount, name);
  public SemaphoreAsync(int initialCount, int maximumCount, string name, out bool createdNew, SemaphoreSecurity semaphoreSecurity) => _semaphore = new Semaphore(initialCount, maximumCount, name, out createdNew, semaphoreSecurity);

  public static SemaphoreAsync OpenExisting(string name)
  {
    return new SemaphoreAsync(Semaphore.OpenExisting(name));
  }

  public static SemaphoreAsync OpenExisting(string name, SemaphoreRights rights)
  {
    return new SemaphoreAsync(Semaphore.OpenExisting(name, rights));
  }

  public static bool TryOpenExisting(string name, out SemaphoreAsync result)
  {
    if (Semaphore.TryOpenExisting(name, out Semaphore semaphore))
    {
      result = new SemaphoreAsync(semaphore);
      return true;
    }
    result = null;
    return false;
  }

  public static bool TryOpenExisting(string name, SemaphoreRights rights, out SemaphoreAsync result)
  {
    if (Semaphore.TryOpenExisting(name, rights, out Semaphore semaphore))
    {
      result = new SemaphoreAsync(semaphore);
      return true;
    }
    result = null;
    return false;
  }

  public async Task<bool> WaitOne(TimeSpan timeout, CancellationToken ct)
  {
    DateTime start = DateTime.UtcNow;
    while (!_semaphore.WaitOne(0))
    {
      ct.ThrowIfCancellationRequested();
      if (DateTime.UtcNow < start.Add(timeout))
        return false;
      await Task.Delay(100, ct);
    }
    return true;
  }

  public async Task<bool> WaitOne(int millisecondsTimeout, CancellationToken ct)
  {
    DateTime start = DateTime.UtcNow;
    while (!_semaphore.WaitOne(0))
    {
      ct.ThrowIfCancellationRequested();
      if (millisecondsTimeout > 0)
      {
        if (DateTime.UtcNow < start.AddMilliseconds(millisecondsTimeout))
          return false;
      }
      await Task.Delay(100, ct);
    }
    return true;
  }

  public async Task<bool> WaitOne(CancellationToken ct)
  {
    while (!_semaphore.WaitOne(0))
    {
      ct.ThrowIfCancellationRequested();
      await Task.Delay(100, ct);
    }
    return true;
  }

  public SemaphoreSecurity GetAccessControl()
  {
    return _semaphore.GetAccessControl();
  }

  public int Release()
  {
    return _semaphore.Release();
  }

  public int Release(int releaseCount)
  {
    return _semaphore.Release(releaseCount);
  }

  public void SetAccessControl(SemaphoreSecurity semaphoreSecurity)
  {
    _semaphore.SetAccessControl(semaphoreSecurity);
  }

  #region IDisposable Support
  private bool disposedValue = false; // To detect redundant calls
  void Dispose(bool disposing)
  {
    if (!disposedValue)
    {
      if (disposing)
      {
        // TODO: dispose managed state (managed objects).
        if (_semaphore != null)
        {
          _semaphore.Dispose();
          _semaphore = null;
        }
      }
      disposedValue = true;
    }
  }

  // This code added to correctly implement the disposable pattern.
  public void Dispose()
  {
    // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
    Dispose(true);
  }
  #endregion

}


texts: Switching tabs, with previous/next arrows, using jQuery

texts:
You can find a JSFiddle demo of my tabs.

The jQuery tabs work well as intended. However I was asked to include arrows alongside the tabs so readers could navigate through tabs using them instead of the tab titles alone.

So I used:

$("li.tab").click( function() {
  $('#div1').removeClass( 'hide' );
  $('#div2').removeClass( 'hide' );
  $('#div3').removeClass( 'hide' );
  $('#div1').removeClass( 'show' );
  $('#div2').removeClass( 'show' );
  $('#div3').removeClass( 'show' );
} );
$("a.rightarrow1").click( function() {
  $('#div1').addClass( 'hide' );
  $('#div2').addClass( 'show' );
  $('#div2').removeClass( 'hide' );
  $('#div3').addClass( 'hide' );
  $('li.tab2').addClass( 'current' );
  $('li.tab1').removeClass( 'current' );
  $('li.tab3').removeClass( 'current' );
} );
$("a.leftarrow1").click( function() {
  $('#div1').addClass( 'hide' );
  $('#div2').addClass( 'hide' );
  $('#div3').addClass( 'show' );
  $('#div3').removeClass( 'hide' );
  $('li.tab3').addClass( 'current' );
  $('li.tab2').removeClass( 'current' );
  $('li.tab1').removeClass( 'current' );
} );
$("a.rightarrow2").click( function() {
  $('#div1').addClass( 'hide' );
  $('#div2').addClass( 'hide' );
  $('#div3').addClass( 'show' );
  $('#div3').removeClass( 'hide' );
  $('li.tab3').addClass( 'current' );
  $('li.tab2').removeClass( 'current' );
  $('li.tab1').removeClass( 'current' );
} );
$("a.leftarrow2").click( function() {
  $('#div1').addClass( 'show' );
  $('#div1').removeClass( 'hide' );
  $('#div2').addClass( 'hide' );
  $('#div3').addClass( 'hide' );
  $('li.tab1').addClass( 'current' );
  $('li.tab2').removeClass( 'current' );
  $('li.tab3').removeClass( 'current' );
} );
$("a.rightarrow3").click( function() {
  $('#div1').addClass( 'show' );
  $('#div1').removeClass( 'hide' );
  $('#div2').addClass( 'hide' );
  $('#div3').addClass( 'hide' );
  $('li.tab1').addClass( 'current' );
  $('li.tab2').removeClass( 'current' );
  $('li.tab3').removeClass( 'current' );
} );
$("a.leftarrow3").click( function() {
  $('#div1').addClass( 'hide' );
  $('#div2').addClass( 'show' );
  $('#div2').removeClass( 'hide' );
  $('#div3').addClass( 'hide' );
  $('li.tab2').addClass( 'current' );
  $('li.tab3').removeClass( 'current' );
  $('li.tab1').removeClass( 'current' );
} );

It's long, but it works. But can it be made more elegant?


texts:
I was wondering... In the standard library of some Prolog systems, there are meta-predicates like maplist and foldl.

In general, when using meta-predicates (like the ones above) with dcg we always need the "foldl" variants. What about the following mapfoldl/5 (mapfoldl//3)?

mapfoldl(P_4,Xs,Zs,S0,S) :-
   list_mapfoldl_(Xs,Zs,S0,S,P_4).

list_mapfoldl_([],[],S,S,_).
list_mapfoldl_([X|Xs],[Y|Ys],S0,S,P_4) :-
   call(P_4,X,Y,S0,S1),
   list_mapfoldl_(Xs,Ys,S1,S,P_4).

What's your take on this code? They isn't this (or something very similar) already in the stdlibs?


texts: Mars Rover challenge in Python - general feedback

texts:
I have given the Mars Rover challenge a go in Python as DSA practice.

Here is the challenge:

  A rover’s position and location is represented by a combination of x and y co-ordinates and a letter representing one of the four cardinal compass points. The plateau is divided up into a grid to simplify navigation. An example position might be 0, 0, N, which means the rover is in the bottom left corner and facing North.

  In order to control a rover , NASA sends a simple string of letters. The possible letters are ‘L’, ‘R’ and ‘M’. ‘L’ and ‘R’ makes the rover spin 90 degrees left or right respectively, without moving from its current spot. ‘M’ means move forward one grid point, and maintain the same heading._

  Test Input:

  5 5

  1 2 N

  LMLMLMLMM

  3 3 E

  MMRMMRMRRM

  Expected Output:

  1 3 N

  5 1 E

I am still relatively new to Python so know this is a bit basic - but I wondered if I could get some general feedback on my code for best coding practice?

RIGHT_ROTATE = {
    'N':'E',
    'E':'S',
    'S':'W',
    'W':'N'
}

LEFT_ROTATE = {
    'N':'W',
    'W':'S',
    'S':'E',
    'E':'N'
}

class MarsRover():

    def __init__(self, X, Y, direction):

        self.X = X
        self.Y = Y
        self.direction = direction

    def rotate_right(self):

        self.direction = RIGHT_ROTATE[self.direction]

    def rotate_left(self):

        self.direction = LEFT_ROTATE[self.direction]

    def move(self):

        if self.direction == 'N':
            self.Y += 1
        elif self.direction == 'E':
            self.X += 1
        elif self.direction == 'S':
            self.Y -= 1
        elif self.direction == 'W':
            self.X -= 1

    def __str__(self):

        return str(self.X) + " " + str(self.Y) + " " + self.direction

    @classmethod
    def get_rover_position(self):

        position = input("Position:")
        X = int(position[0])
        Y = int(position[2])
        direction = position[4]
        return self(X, Y, direction)

class Plateau():

    def __init__(self, height, width):

        self.height = height
        self.width = width

    @classmethod
    def get_plateau_size(self):

        plateau_size = input("Plateau size:")
        height = int(plateau_size[0])
        width = int(plateau_size[2])
        return self(height, width)

def main():

    plateau = Plateau.get_plateau_size()

    while True:

        rover = MarsRover.get_rover_position()

        current_command = 0
        command = input("Please input directions for rover.")
        command_length = len(command)

        while current_command <= command_length - 1:

            if command[current_command] == 'L':
                rover.rotate_left()
                current_command += 1
            elif command[current_command] == 'R':
                rover.rotate_right()
                current_command += 1
            elif command[current_command] == 'M':
                rover.move()
                current_command += 1

        result = str(rover)
        print(result)

if __name__ == '__main__':

    main()


texts: Graph represented by an adjacency matrix in C++

texts:
I'm working on my data structures knowledge and wanted to create a graph with a small DFS driver which simply prints the nodes as it visits them. Here's my graph class:

#ifndef GRAPH_H_
#define GRAPH_H_

#include <stack>
#include <random>
#include <iterator>
#include <unordered_map>
#include <unordered_set>

template <typename T>
class Graph {
  public:
    Graph(bool directed) : directed{directed}, adj_matrix{} {}
    ~Graph() {}
    void add_edge(const T& start, const T& end) {
      adj_matrix[start][end] = true;
      adj_matrix[start][start] = false;
      adj_matrix[end][end] = false;
      adj_matrix[end][start] = directed ? false : true;
    }

    void DFS(T const *start=nullptr) const {
      if(!adj_matrix.size())
        return;
      if(start==nullptr) {
        DFS_helper(get_random_node());
      } else {
        DFS_helper(*start);
      }
    }

    void DFS_helper(const T& start) const {
      std::unordered_set<T> visited;
      std::stack<T> s;
      s.push(start);
      while(!s.empty()) {
        T top = s.top();
        s.pop();
        // If top is unvisited
        if(visited.find(top) == std::end(visited)) {
          // visit it
          visited.insert(top);
          std::cout << top << ' ';
          for(const auto& adj_node: get_adjacent_nodes(top)) {
             s.push(adj_node);
          }
        }
      }
      std::cout << '\n';
    }

  private:
    std::vector<T> get_adjacent_nodes(const T& v) const {
        std::vector<T> adj;
        for(const auto& pair: adj_matrix.at(v)) {
            T neighbor = pair.first;
            bool is_neighbor = pair.second;
            if(is_neighbor) {
                adj.push_back(neighbor);
            }
        }
        return adj;
    }
    T get_random_node() const {
      auto random_it = std::next(std::begin(adj_matrix), std::rand() % (adj_matrix.size()-1));
      return random_it->first;
    }
    const bool directed;
    std::unordered_map<T, std::unordered_map<T, bool>> adj_matrix;
};

#endif //GRAPH_H_

And here's my driver (inspired from this Wikipedia image):

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

int main() {
  bool directed = false;
  Graph<char> g(directed);
  g.add_edge('A', 'B');
  g.add_edge('B', 'D');
  g.add_edge('A', 'E');
  g.add_edge('E', 'F');
  g.add_edge('A', 'C');
  g.add_edge('C', 'G');
  g.add_edge('B', 'F');

  char a = 'A';
  g.DFS(&a);
}

I'm interested in any tips or recommendations!


texts: Checking user permission, where permission is granted for specific EmployeeGroup that has self reference

texts:
The users get permissions to do specific things for a specific group of employees. These employee groups have a self reference. So an employee group (C) can be a child of group (B), and group (B) is child of (A). The user is granted permission to employee group (A), so if I want to check if the permission is granted for that user on employee group (C) it should give me true because the user is granted the permission on the parent or grandparent group. Currently, I am using this method and it works fine but I find it ugly and complicated a bit. Is there a more elegant way to do it?
This is the method:
public static bool CheckPermission(Session session, string right, int? emplooyeGroupID = null)
{
    using (Context db = new Context())
    {
        bool pass = false;
        var assigns = db.SecurityAssigns
            .Where(g => g.UserID == session.UserID);

        // if employeeGroupID is supplied we need to do some work here...
        if (emplooyeGroupID.HasValue)
        {
            // first, we get all 'groups' that have the requested SecurityRight
            assigns = assigns.Where(g => g.SecurityGroup.SecurityRightsInGroups.Any(r => r.SecurityRight.Right == right));

            foreach (var grp in assigns)
            {
                // if the employee group matches, then its a pass
                if (grp.EmployeeGroupID == emplooyeGroupID)
                {
                    pass = true;
                    break;
                }

                // if we reach here, it means the EmployeeGroupID does not match the EmployeeGroupID assigned for the SecurityRight.
                // so we need to check if the requested EmployeeGroupID is a child of the EmployeeGroupID assigned to the SecurityRight
                var curGroup = db.EmployeeGroups.Single(g => g.ID == emplooyeGroupID);

                // loop through parents of the requested EmployeeGroup all the way up
                while (curGroup.ParentGroupID.HasValue)
                {
                    // is the parent authorized?
                    if (curGroup.ParentGroupID == grp.EmployeeGroupID)
                    {
                        pass = true;
                        break;
                    }

                    // parent is not authorized, go up one more step
                    curGroup = db.EmployeeGroups.Single(g => g.ID == curGroup.ParentGroupID);
                }
            }

        }
        else
        {
            pass = assigns.Any(g => g.SecurityGroup.SecurityRightsInGroups.Any(r => r.SecurityRight.Right == right));
        }

        if (!pass)
            throw new FaultException("Not Authorized!", new FaultCode(Common.ErrorCodes.NOT_AUTHORIZED_ERROR_CODE));

        return true;
    }
}

This is some the tables I am working with in the code above:

P.S. I am not a programmer and I didn't get any education on programming, it is just a hobby. So go easy on me if my coding is ugly :)


texts: Generate a list of the last 100 modified folders

texts:
This is a subroutine I have written as a part of an Excel VBA script. I usually write vb.net or Python but I need the final results for this project in Excel so I'm using VBA.

My initial task is to get the latest 5-100 folders by date last modified (user selects the number of folders). Looking at this question on SO, I found out how to get a list of folders and store it in the cells in excel with the date last modified. This can then be sorted by date modified and I can then work my way down the list for however many folders the user selected.

The code puts this list into a new sheet called Folders, clearing out any old versions if needed.

I can't help but feel that storing the list in cells isn't the best way to do it. I would have thought it would be better to have it in some sort of dictionary or list but I could be mistaken.

Currently, there are around 1000 subfolders in the directory to search and this could potentially grow over 10,000 in the future. Will this approach still work well with that many folders?

Are there any other general improvements I could make?

Sub Get_Sorted_Folder_List(results_dir As String)

    ' Var Declarations
    Dim fso As New FileSystemObject
    Dim fs_folder As Folder
    Dim folder_sheet As Worksheet

    ' Setup "Folders" worksheet
    ' Detect if it already exists, delete if it does
    Application.DisplayAlerts = False
    Err.Clear
    On Error Resume Next
    Set folder_sheet = Sheets("Folders")
    If Err = 0 Then folder_sheet.Delete
    On Error GoTo 0

    ' Create new Folders sheet
    Set folder_sheet = ThisWorkbook.Sheets.Add(After:= _
                            ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
    folder_sheet.Name = "Folders"
    folder_sheet.Select
    Range("A1").Select
    Columns(1).ColumnWidth = 10
    Columns(2).ColumnWidth = 18

    ' Get list of files
    Set fs_folder = fso.GetFolder(results_dir)
    Dim counter As Integer
    counter = 0

    For Each Folder In fs_folder.SubFolders
        counter = counter + 1
        Cells(counter, 1).Value = Folder.Name
        Cells(counter, 2).Value = Folder.DateLastModified
    Next

    ' Sort newest to oldest
    folder_sheet.Sort.SortFields.Clear
    folder_sheet.Sort.SortFields.Add Key:= _
        Range(Cells(1, 2), Cells(counter, 2)), SortOn:=xlSortOnValues, _
        Order:=xlDescending, DataOption:=xlSortNormal

    With folder_sheet.Sort
        .SetRange Range(Cells(1, 1), Cells(counter, 2))
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

End Sub


texts: Override prototype inside of constructor of ES6 class for dependency injection

texts:
We implemented a small dependency injection mechanism which we use in our project. Now after 2 years of developing our project we need our classes to know who instantiated them via dependency injection. Therefore we pass to the constructor of every class which is "injectable" a property called creator. To achieve this we had two options:

create a super-class which every "injectable" has to extend
create an interface which every "injectable" has to implement

Both options had downsides but we decided to go with the second option because we didn't want to force classes to extend "injectable" which do not have to do anything with "injection" and only need to extend "injectable" because we can not do multiple inheritance. This lead to the problem that we had to touch every class and clutter them with properties which are only used for DI. Since we use TypeScript we tried to do something with a class decorator, we got the idea from their last example on https://www.typescriptlang.org/docs/handbook/decorators.html#class-decorators.

This works quite well but there was the problem, that the creator property was not available in the constructor. Since you can not alter the constructor of an ES6 class we came up with the following solution:

export function injectable(Base) {
    return class extends Base {
        public _creator_;
        constructor(...args) {
            const creator = args.shift();
            Base.prototype._creator_ = creator;
            super(...args);
            Base.prototype._creator_ = null;
            delete Base.prototype._creator_;
            this._creator_ = creator;
        }
    };
}

Now in the DI basically the following happens (this is more "pseudo-code" because we use TypeScript and the original code is a little bit more involved):

// "pseudo-code" because we use TypeScript and the original code is a little bit more involved
class Container {

    static lookup(specifier, requester) {
        const instance = Container._find(specifier, requester._creator_);
        if (instance) {
            return instance;
        }
        // call to injectable is normally done by TypeScript class decorator
        const ExtendedBase = injectable(Container._findClassDefinition(specifier));
        const newInstance = new ExtendedBase(requester._creator_);
        this._set(specifier, newInstance, creator);
    }

    static _find(specifier, creator) {
        // return the instance which belongs to the specifier if it's already created for the given creator
    }

    static _set(specifier, instance, creator) {
        // set the instance of a given specifier for the creator
    }

    static _findClassDefinition(specifier) {
        // find the class definition to a specifier
    }
}

class X {
    constructor() {
        // this is done by a property decorator by TypeScript
        this._injectedService = Container.lookup('injectedService', this);
    }

    run() {
        this._injectedService.doStuff();
    }
}

class Main {
    constructor() {
        this._creator_ = getNextCreator();
        this._x = Container.lookup('x', this._creator_);
    }

    run() {
        this._x.run();
    }
}

const main = new Main();
main.run();

At first glance, this works quite well for us but we are not quite sure if this is really a sophisticated solution or if we can run into troubles if there are concurrent calls to DI.inject(X). We know that JavaScript is not multi-threaded but maybe there are problems with different contexts like WebWorkers or ServiceWorkers etc. We are especially worried because we touch the prototype of the base class. So our question is mostly around the function injectable.

Would be great to get some feedback of you so we can evaluate pros and cons of our approach :-)

EDIT: updated the second code snippet due to @Blindman67's feedback (see the comments of the question)


texts:
I need to concatenate two content_tag and it works but it seems a little messy to me. Any thoughts on how may I refactor this?

def format_price(money)
  mny = get_price_string(money).to_money
  str = content_tag(:span, @visitor.currency.symbol.html_safe, class: 'pounds')
  str << mny.format(no_cents: true, symbol: '')
  str << content_tag(:span, mny.format[-3, 3], class: 'pence') unless condition?
end


texts: Given an array of integers, return all pairs that add up to 100

texts:
I was recently given this programming challenge on an interview, and I decided to use javascript to solve it. I did, but I'm not happy with my implementation. I can't help thinking there must be a better way of doing this.

The exercise goes like this:

  Given an array of integers, write a function that returns an array of
  each pair of integers that add up to 100. The input is

    [0, 1, 100, 99, 0, 10, 90, 30, 55, 33, 55, 75, 50, 51, 49, 50, 51, 49, 51]

  and the function should return something like this (the order is not
  important).

    [ [0,100], [1,99], [10,90], [50,50], [49,51] ]

My implementation looks like this, is there a different approach out there?

var sample_data = [0, 1, 100, 99, 0, 10, 90, 30, 55, 33, 55, 75, 50, 51, 49, 50, 51, 49, 51]

function process(data){

    var result = []
    var a;
    var b;

    for (var i=0; i < data.length; i++) {

        a = data[i];

        for (var j=0; j < data.length; j++) {

            b = data[j]

            if ( (parseInt(a) + parseInt(b)) === 100 && result.indexOf(a+","+b) == -1 && result.indexOf(b+","+a ) == -1 ) {
               result.push( a+","+b )
            }

        }
    }

    for (var i=0; i < result.length; i++) {
        result[i] = result[i].split(',')
    }

    return result
}

process(sample_data);


texts: Stack implementation using vectors with no overflow version 1.0

texts:
This is an implementation of a stack where I have used vectors. Can anyone please review it and let me know how I can improve this code and overall coding practice?

    #include"iostream"
class Mystack
{
private:
    int *A;
    int top;
    int size;
public:
    Mystack(int capacity);
    void push(int x);
    int pop();
    int topElement();
    void print();
    bool isEmpty();
};
Mystack::Mystack(int capacity)
{
    top = -1;
    size = capacity;
    A = new int[capacity];
}
void Mystack::push(int x)
{

    if (top + 1 == size)
    {
        int *vec = new int[size + size];
        for (int i = 0; i < size; i++)
        {
            vec[i] = A[i];
        }
        A = vec;
        size = size * 2;
        top++;
        A[top] = x;
        return;
    }
    else
    {
        top++;
        A[top] = x;
    }
}
int Mystack::pop()
{
    if (isEmpty())
    {
        std::cout << "Stack Underflow" << std::endl;
    }
    else
    {
        std::cout << "The popped element is" << A[top];
        return A[top--];
    }
    return 0;
}
bool Mystack::isEmpty()
{
    if (top == -1)
    {
        std::cout << "Is Empty" << std::endl;
        return true;
    }
    else
    {
        std::cout << "Not Empty" << std::endl;
        return false;
    }
}
int Mystack::topElement()
{
    std::cout << "The top element is : " << A[top];
    return A[top];
}
void Mystack::print()
{
    for (int i = 0; i <= top; i++)
    {
        std::cout << A[i] << " ";
    }
}
void main()
{
    Mystack s1(10);
    int num, ch = 1;
    while (ch >0)
    {
        std::cout << "\n1. PUSH" << std::endl;
        std::cout << "2. TOP" << std::endl;
        std::cout << "3. IsEmpty" << std::endl;
        std::cout << "4. POP" << std::endl;
        std::cout << "5. EXIT" << std::endl;
        std::cout << "6. Print" << std::endl;
        std::cout << "Enter the choice" << std::endl;
        std::cin >> ch;
        switch (ch)
        {
        case 1:
            std::cout << "Enter the number to be pushed" << std::endl;
            std::cin >> num;
            s1.push(num);
            break;
        case 2:
            std::cout << "Get the TOP Element" << std::endl;
            s1.topElement();
            break;
        case 3:
            std::cout << "Check Empty" << std::endl;
            s1.isEmpty();
            break;
        case 4:
            std::cout << "POP the element" << std::endl;
            s1.pop();
            break;
        case 5: exit(0);
        case 6:
            s1.print();
            break;
        }
    }
    system("pause");
}


texts: Sorting strings with certain restrictions

texts:
I want to sort a string which contains words and integers with the restriction that if the nth element in the list is an integer it must remain an integer and if it is a word, it must remain a word.

Currently, what I am doing is splitting the input string on spaces, putting the words and integers into their own lists, sorting them appropriately by mapping to a different list, and then injecting the sorted words/integers back into the original input list.

I am trying to find comments on improve the code or looking for a different approach to the problem if there is a better one. Does anyone have any comments?

http://ideone.com/X2pPfg

justWords   = {}
words       = []

justNums    = {}
nums        = []

# Check if value in the input is an integer or a word
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

# Replace the values in the dictionary with the correctly sorted words/integers
def go_through(theDict, theList):
    counter = 0
    for k,v in theDict.iteritems():
        theDict[k]   = theList[counter]
        counter      = counter + 1
    return theDict

# Replace the values in the original input
 # list with correctly sorted values of the word/int dicts
def inject(theDict, theList):
    for k,v in theDict.iteritems():
        theList[k] = v
    return theList

if __name__ == "__main__":

    splitInput  = (raw_input("")).split()

    # Sort the words and numbers into their own lists as tuples
    for i,j in enumerate(splitInput):
        if is_number(j):
            justNums[i]  = j
            nums.append(j)
        elif not is_number(j):
            justWords[i] = j
            words.append(j)

    print("%s\n%s\n" % (justWords, justNums))

    words = sorted(words)
    nums  = sorted(nums)

    print("%s\n%s\n" % (words, nums))

    # Replace the values in the dictionaries with the values in the sorted list
    justWords = go_through(justWords, words)
    justNums  = go_through(justNums, nums)

    print("%s\n%s\n" % (justWords, justNums))

    # Inject correctly maped sorted words into the original list
    splitInput = inject(justWords, splitInput)
    splitInput = inject(justNums, splitInput)

    print("%s" % (' '.join(splitInput)))

Input:

car truck 8 4 bus 6 1

Output:

{0: 'car', 1: 'truck', 4: 'bus'}
{2: '8', 3: '4', 5: '6', 6: '1'}

['bus', 'car', 'truck']
['1', '4', '6', '8']

{0: 'bus', 1: 'car', 4: 'truck'}
{2: '1', 3: '4', 5: '6', 6: '8'}

bus car 1 4 truck 6 8


texts:
Background
I have a code that basically caches file. The way it works is it will first check if the file exists on the local drive and if it does if there is a flag passed called validate_file_size then it will do another check to see if the size of the file on local drive equals the size of the file on S3. if they equal we assume the local file is the most recent version and if they don't then we need to download the latest version.
CODE
  def cache_file(self, s3_path_of_file: str, local_path: Path, file_name: str, validate_file_size: bool = True) -> None:
        bucket, key = s3.deconstruct_s3_url(f"{s3_path_of_file}/{file_name}")
        is_file_size_valid = True
        if not (local_path / file_name).exists():
            os.makedirs(local_path, exist_ok=True)
            try:
                s3_client().download_file(bucket, key, f"{local_path}/{file_name}")
                os.chmod(local_path / file_name, S_IREAD | S_IRGRP | S_IROTH)
            except botocore.exceptions.ClientError as e:
                if e.response["Error"]["Code"] == "404":
                    raise FileNotFoundError
        elif validate_file_size:
            is_file_size_valid = self._is_file_size_equal(
                s3_path_of_file, local_path, file_name
            )
            if not is_file_size_valid:
                try:
                    s3_client().download_file(bucket, key, f"{local_path}/{file_name}")
                    os.chmod(local_path / file_name, S_IREAD | S_IRGRP | S_IROTH)
                except botocore.exceptions.ClientError as e:
                    if e.response["Error"]["Code"] == "404":
                        raise FileNotFoundError
            else:
                logger.info("Cached File is Valid!")

ISSUE
I am wondering if there is a better way to organize my if else statements so my code is cleaner and less redundant. I am not particularly happy about this block in particular that is repeated twice.
 try:
     s3_client().download_file(bucket, key, f"{local_path}/{file_name}")
     os.chmod(local_path / file_name, S_IREAD | S_IRGRP | S_IROTH)
 except botocore.exceptions.ClientError as e:
     if e.response["Error"]["Code"] == "404":
         raise FileNotFoundError

One obvious choice is to take it out as a separate function but I am almost wondering if i can avoid that and organize my if else statement in a way where i don't really repeat this try except block twice.


texts: Allowing a user to draw their own avatar in turtle

texts:
I am working on a turtle project where the user can draw their own avatar.
The thing is, I want the user to be able to decide whether the turtle they drew will be filled, or not.
The filled part is simple, as by default, the polies will get filled,
but the only way I know how to avoid filling is to retrace the lines so that the end of the line meets the start of the line.
Is there a built-in method or a more efficient way to keep the polies empty?
The problem with my current method is that the more lines (parameter) is used for turtle, the more rocky the program runs (the area doesn't influence the smoothness of the program).
import turtle

wn = turtle.Screen()

pen = turtle.Turtle('circle')
pen.shapesize(0.1, 0.1)

cor = []

# function to draw with the pen
def drag(x, y):
    wn.tracer(0)
    pen.goto(x, y)
    cor.append(pen.pos())

# function to break out of while loop
def fill():
    global done
    done = True

# function to break out of while loop and set fill to False
def nofill():
    global done, fill
    done = True
    fill = False

wn.listen()
wn.onkeypress(fill, 'f')
wn.onkeypress(nofill, 'n')

pen.ondrag(drag)

done = False
fill = True

while not done:
    wn.update()

pen.begin_poly()

if fill:
    for c in cor:
        pen.goto(c)
else:
    for c in cor[::-1]: # first go backards, then forward to avoid fill
        pen.goto(c)
    for c in cor:
        pen.goto(c)

pen.end_poly()

wn.register_shape("mypen", pen.get_poly())
wn.clear()

example = turtle.Turtle('mypen')

Example with fill:

Run the above code.

Draw a shape.

Press f

Example without fill:

Run the above code.

Draw a shape.

Press n


texts: Encapsulation of putpixel is terribly slow in JavaFx

texts:
I am trying to write a simple rendering engine in JavaFx and I manage encapsulate putpixel in the way that I pass x,y coordinates and color and it draws pixel of that color to the screen. I also wrote drawLine() that draws line between x1,y1 and x2,y2.

Today I wrote a function drawRectangle() which uses drawLine(), but the problem is that drawing rectangles is immensely slow ( 300x300 px rectangle takes around 3 seconds to draw ). I think it is because how I am accessing the backbuffer and drawing pixels.

I am including snippets of code for putpixel, drawLine and drawRect have pretty good time complexity and they are for sure not causing bottlenecks:

public class Graphics
{
   private int SCREEN_WIDTH = 600;
   private int SCREEN_HEIGHT = 600;

   private Canvas          canvas; //pixel buffer
   private GraphicsContext gc;
   private WritableImage   img; //layer
   private PixelWriter     pw;

   public Graphics()
   {
      this.canvas = new Canvas( SCREEN_WIDTH,SCREEN_HEIGHT );
      this.gc = canvas.getGraphicsContext2D();
      this.img = new WritableImage( SCREEN_WIDTH,SCREEN_HEIGHT ); //layer
      this.pw  = img.getPixelWriter();
   }

   public void createWindow( Stage primaryStage )
   {
      Stage window = primaryStage;

      window.setOnCloseRequest( new EventHandler< WindowEvent>()
      {
      public void handle( WindowEvent e )
         {
            Platform.exit();
            System.exit( 0 );
            Platform.setImplicitExit( true );
         }
      });

      window.setTitle( "Fasa3D" );

      GridPane grid = new GridPane();
      grid.getChildren().addAll( this.canvas ); //put pixel buffer into layout

      Scene scene = new Scene( grid,SCREEN_WIDTH,SCREEN_HEIGHT );
      window.setScene( scene );
      window.show(); //present pixel buffer
   }

   public void putPixel( int x,int y,Color c )
   {
      this.pw.setColor( x,y,c );     //accessing pixel by coord;
      this.gc.drawImage( img,0,0 ); //draw layer onto pixel buffer
   }
}

I would be infinitely thankful if you could please help me out with optimization. The whole repo is here.


texts:
Given a m * n grids, and one is allowed to move up or right, find the different number of paths between two grid points.

My major idea is, if move r steps right, u steps up, we can find (1) solutions for r-1 steps right and u steps up, then combine with one final right step (2) solutions for r steps right and u-1 steps up, then combine with one final up step.

I use a dynamic programming matrix dp to track number of path. For example, dp[i][j] means if we move i steps right and j steps up.

Any advice on code bugs, smarter ideas in terms of algorithm time complexity or code style advice is appreciated.

def move_right_up_count(rights, ups):
    dp = [[0] * (ups+1) for _ in range(1+rights)]
    for i in range(1,rights+1):
        dp[i][0] = 1
    for j in range(1, ups+1):
        dp[0][j] = 1
    for i in range(1, rights+1):
        for j in range(1, ups+1):
            dp[i][j] = dp[i-1][j] + dp[i][j-1]
    return dp[-1][-1]

if __name__ == "__main__":
    print move_right_up_count(2,3)


texts:
I am trying to solve as many issues as possible with my Database Class and bind statements as far as possible without actually doing it in the front-end. The goal is to do all of the heaving lifting for PHP Developers and Web Designers as possible to make their job even more easier than other PHP frameworks.

The Database class is my main worry to make sure that I keep security with simplexity.

class Database {
// Instance of the Database and Error
private $db;
private $error;
private $stmt;

    public  function  __construct ()  {
    //  Init the database connection
    //  Sets the connection type
    $host = 'mysql:host' . $this->_hostname ';dbname' . $this->_database;

    //  Sets the connection options
    $options = array(
                     PDO :: ATTR_PERSISTENT  =>  TRUE ,
                     PDO::ATTR_ERRMODE    => PDO:ERRMODE_EXCEPTION
                    );

    try {
        //  Generates the Database connection of our class
        this->db = new PDO($host, $this->_username, $this->_password, $options);
    }
    catch(PDOException $exception) {
        //  Catches all errors from the Database connection
        $this->error = $exception->getMessage();
    }
}

The instance of the Database is defined and called in __construct() to allow it to be called globally in other classes.

For queries to be done, I managed a small (secure?) work around in the form of functions

public function execute() {
    //  Executes our SQL query
    return $this->stmt->execute();
}

public function results() {
    //  Returns all of the results from the table
    $this->execute();
    return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}

public  function  result ()  {
    //  Returns one of the results from the table
    $this->execute();
    return $this->stmt->fetch(PDO::FETCH_ASSOC);
}

With my knowledge, this is the most secure route of handling PDO and information unless I am wrong?

The other way, which seems to be more dangorious and common is to do $db->prepapre() and also db->execute() directly.

Am I handling the database class more securely than directly allowing the PDO built-in functions to do it directly in my class's code and pages?


texts:
What?

I have a reference counted dynamic byte array written in C. I'm currently using this implementation in a FIFO fashion. Particularly reading data from files into the arrays, then parsing the data in the array byte by byte.

I'm looking for feedback on anything! Even the decision to use a dynamic byte array versus using a linked list or any other data structure.

Edit: I'm trying to follow the Linux Kernel coding style, so I'm looking for feedback on how well I follow that convention.

Files

Header

#ifndef DATA_BYTE_ARRAY
#define DATA_BYTE_ARRAY

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <assert.h>
#include <string.h>

#include "../memory.h"

/**
 * Dynamic array that grows when it's full (given that
 * the util functions in this module are used).
 *
 * For each grow it uses the current length doubled. See
 * byte_array_push for more info.
 */

struct byte_array {
        uint8_t refs;
        uint32_t length;
        uint32_t capability;
        uint8_t *bytes;
};

/**
 * Creates a byte array with the given length.
 *
 * Values of the returned struct:
 * - 1 reference
 * - All bytes will be set to 0
 * - Current position will be set to 0
 * - Capability will reflect how many bytes are allocated. Which is
 *   the same as given capability.
 */

struct byte_array *byte_array_create(uint32_t capability);

/**
 * Adds the given input at the current position of the array.
 *
 * Note that if the pointer to the byte array is NULL an assertion will crash
 * the program.
 *
 * If the byte array is full more memory will be allocated. The amount
 * of new memory that will be allocated is the current amount doubled.
 */

void byte_array_push(struct byte_array *a, uint8_t input);

void byte_array_incref(struct byte_array *a);

void byte_array_decref(struct byte_array *a);

#endif

Source

#include "byte_array.h"

#define NEW_CAPABILITY a->capability * 2

static void zero_init_bytes(struct byte_array *a,
                            uint32_t offset,
                            uint32_t nmemb)
{
        uint8_t *bytes = a->bytes;
        bytes += offset;
        memset(bytes, 0, nmemb);
}

struct byte_array *byte_array_create(uint32_t capability)
{
        struct byte_array *result = assert_malloc(sizeof(*result));
        result->refs = 1;
        result->length = 0;
        result->capability = capability;
        result->bytes = assert_calloc(capability, sizeof(uint8_t));

        return result;
}

void byte_array_push(struct byte_array *a, uint8_t input)
{
        assert(a != NULL);

        if (a->length == a->capability) {
                void *tmp = assert_realloc(a->bytes, NEW_CAPABILITY);

                a->bytes = tmp;

                zero_init_bytes(
                        a,
                        a->capability,
                        NEW_CAPABILITY - a->capability
                );

                a->capability = NEW_CAPABILITY;
        }

        a->bytes[a->length++] = input;
}

void byte_array_incref(struct byte_array *a)
{
        assert(a != NULL);

        a->refs++;
}

void byte_array_decref(struct byte_array *a)
{
        assert(a != NULL);

        if (--a->refs != 0) return;

        free(a->bytes);
        free(a);
}


texts: Parsing a fixed-size message using variable length array in C

texts:
My C program has to parse a fixed-length message like this:
uint8_t message[8] = {80, 75, 73, 71, 1, 1, 1, 1};

another message could be:
uint8_t message[8] = {80, 75, 73, 71, 41, 42, 1, 1};

The message contains an ASCII string and 1 shows the end of string. So the actual length of the first message is 4 and the second message is 6.
I use this method to extract the message:
1. Counting the message length
2. Initializing a variable length array with this value.
3. Using memcpy to copy the bytes.

decoder.h
#ifndef DECODER_H_INCLUDED
#define DECODER_H_INCLUDED

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

#define LENGTH 100
void parse(uint8_t * message);
void get_address(char * addr, int size);
uint8_t get_size(void);

#endif // DECODER_H_INCLUDED

decoder.c
#include "decoder.h"

// Global variables in library
uint8_t parsed_message[LENGTH];
uint8_t len = 0;

void parse(uint8_t * message)
{
len = 0;
for (int i = 0; i < LENGTH; i++)
    {
        if (message[i] != 1)
        {
            parsed_message[i] = message[i];
            len++;
        }
        else
        {
            parsed_message[i] = '\0';
            len++;
            break;
        }

    }
}

void get_address(char * addr, int size)
{
    memcpy(addr, parsed_message, size);
}

uint8_t get_size(void)
{
    return len;
}

In the main function:
#include <stdio.h>
#include <stdlib.h>
#include "decoder.h"

int main(void) {

    uint8_t input[8] = {80, 75, 73, 71, 1, 1, 1, 1};
    parse(input);

    char addr[get_size()];
    get_address(addr, get_size());
    printf("==== %s ==== ADDRESS\n", addr);

    return 0;
}

I use GCC compiler and C99 standard in ARM-Based 32-bit micro-controller.
My question is that is this method safe? Or I should use another approach.


texts: Updating all members of a struct in database

texts:
This function is part of our company's project code.
The following function updates six members of struct CpGSMTimeDelayQuery -- t14_cp, T14_au, Tdl_fib_f, Tul_fib_f, Tdl_cp_f, Tul_cp_f -- in the database.

It contains six similar blocks. These blocks do the same thing: read a specific register, calculate the member value using a specific formula, and then set database.

typedef unsigned int    Uint32;

void FpgaAdapter::UpdateCpGsmDelayTime()
{
    Uint32 regvalue(0);
    Uint32 result(0);
    float tmp;

    if (ReadReg(0x98, regvalue)) {
        result = (float)regvalue * 6.51;
        SetStructElementToDB("CpGSMTimeDelayQuery", "t14_cp", result);
    }

    if (ReadReg(0x99, regvalue)) {
        result = (float)regvalue * 6.51;
        SetStructElementToDB("CpGSMTimeDelayQuery", "T14_au", result);
    }

    if (ReadReg(0x9c, regvalue)) {
        result = (float)regvalue * 6.51;
        SetStructElementToDB("CpGSMTimeDelayQuery", "Tdl_fib_f", result);
    }

    if (ReadReg(0x9d, regvalue)) {
        result = (float)regvalue * 6.51;
        SetStructElementToDB("CpGSMTimeDelayQuery", "Tul_fib_f", result);
    }

    if (ReadReg(0xa0, regvalue)){
        tmp = (0xff & regvalue) * 32.55;
        result = ( 0xff & (regvalue>>8)) * 1000 + (Uint32)tmp;
        SetStructElementToDB("CpGSMTimeDelayQuery", "Tdl_cp_f", result);
    }

    if (ReadReg(0xa1, regvalue)){
        tmp = (0xff & regvalue) * 32.55;
        result = (0xff & (regvalue>>8)) * 1000 + (Uint32)tmp;
        SetStructElementToDB("CpGSMTimeDelayQuery", "Tul_cp_f", result);
    }
}

How can I refactor this function so that I can use a for loop to update all members of the struct instead of using six similar blocks?

My thought:
Create a map which key is member name, and value is register address and calculation formula. Then loop through the map to update all members in the database.

But, I don't know how to do that because I am not familiar with C++.


texts: Using dynamic methods to build SQL queries in CodeIgniter

texts:
I'm using this class as Modal in my CodeIgniter project, as I'm newbie in CI, I wanna know if this has some issues, I'm using this modal for all queries, like I call this with parameters and it returns results as I wanted. But I'm not sure if it a good idea or it might give some bad impact to structure and security.

<?php
  defined('BASEPATH') OR exit('No direct script access allowed');
  class Crud extends CI_Model {
      public function Read($TableName, $Condition) {
          if ($Condition == '')
              $Condition = ' 1';
          $this->db->where($Condition);
          $data = $this->db->get($TableName);
          return $data->result();
      }
      public function Create($data, $TableName) {
          if ($this->db->insert($data, $TableName))
              return $this->db->insert_id();
          else
              return false;
      }
      public function Update($TableName, $Fields, $Condition) {
          if ($Condition == '')
              $Condition = ' 1';
          $this->db->where($Condition);
          if ($this->db->update($TableName, $Fields))
              return true;
          else
              return false;
      }
      public function Delete($TableName, $Condition) {
          if ($Condition == '')
              $Condition = ' 1';
          $this->db->where($Condition);
          if ($this->db->delete($TableName))
              return true;
          else
              return false;
      }
      public function Count($TableName, $Condition) {
          if ($Condition == '')
              $Condition = ' 1';
          $this->db->where($Condition);
          $result = $this->db->get($TableName);
          if ($result)
              return $result->num_rows();
          else
              return false;
      }

I call this methods like this in my controller

public function changeStatus() {
   $tableName = $this->uri->segment(4);
   $status = $this->uri->segment(5);
   $conditionId = $this->uri->segment(6);
   $condition = " `id` = '$conditionId'";
   $data = [
       'is_active' => $status
   ];
   if($this->Crud->Update($tableName, $data, $condition))
       $this->session->set_flashdata('success', "Success! Changes saved");
   else
       $this->session->set_flashdata('danger', "Something went wrong");
   $referer = basename($_SERVER['HTTP_REFERER']);
   redirect('admin/seller/'.$referer);
}

Please let me know if I can provide more information


texts:
I want to return the title of a record if one exists or the word 'invalid' if not:

    @ID int ,
    @Title nvarchar(50) output
    ...
if exists(select * from MyTable where ID=@ID)
    select @Title = (select Title from MyTable where ID=@ID);
else select @Title = 'invalid';

but I don't have a good feeling with this query.


texts: Simple anagram or permutation generator in Python

texts:
In preparation for a job interview I decided to try and implement the classic find all anagrams of a given string solution. I wanted to see if I could translate a javascript solution into python. This was my attempt:

def anagrams(word):
    if len(word) < 2:
        return word
    else:
        tmp = []
        for i, letter in enumerate(word):
            for j in anagrams(word[:i]+word[i+1:]):
                tmp.append(j+letter)
    return tmp

if __name__ == "__main__":
    print anagrams("abc")


texts: A straightforward method for computing the Binomial probability mass function

texts:
I've been writing up code to test an alternate way of calculating the Binomial probability mass function. The Binomial random variable is the number of heads out of N coin tosses with coins that have probability p of being heads.

The algorithm is pretty simple, we loop through the N coin tosses and update the probability that there are k successes as:

pmf[k] = pmf[k-1] * p +  pmf[k] * (1 - p)

Since we know pmf[k] = 0 for k > n (there can't be more successes than coins tossed so far), we evaluate this line N(N+1)/2 times.

The algorithm works well, is exact, and avoids a number of common pitfalls when computing the Binomial distribution. This is the best implementation I've managed so far, which takes ~190 ms to run on my Dell XPS-15 for N = 15000 and long double p = 0.5.

template <typename T>
std::vector<T> ComputePmf(T p, unsigned int N) {
  std::vector<T> pmf(N + 1, 0.0);
  pmf[0] = 1.0;

  auto k = 0;
  for (auto n = 0; n < N; n++) {
    for (k = n + 1; k > 0; --k) {
      pmf[k] += p * (pmf[k - 1] - pmf[k]);
    }
    pmf[0] *= (1 - p);
  }
  return pmf;
}

Ordinarily I'd hang up my hat and move on, but when I implemented the same algorithm in Julia it ran in 150 ms! Since then I've been stuck trying to figure out how to make my c++ version faster - I've tried:

using different data types (long double works best, maybe due to
SIMD alignment?),
std::array versus std::vector (no difference),
other ways of factoring the inner loop (this is the best I've come up with),
clang and gcc compilers (gcc does slightly better),

It seems like the only real information that I'm not exploiting is the very sequential nature of the data access in this algorithm. Any suggestions?


texts:
I have written the code for a genetic algorithm and have the crossover function, mutation function, parent selector function and a function to transfer genes. Now I want to put it all together and would like to know if the following code is good programming practice or not.

Species Parents[popSize];
Species Children[popSize];

for(int gen = 0 ; gen < 100 ; gen++){
for(int i = 0; i < popSize ; i ++)
{
    int parentA = chooseParent(Parents);
    int parentB = chooseParent(Parents);
    crossOver(Parents[parentA] , Parent[ParentB] , Children[i]);
    Children[i].mutate();
}
for(int i = 0; i < popSize ; i ++)
{
    transfereGenes(Children[i], Parents[i]);
}
}


texts:
I have a query in MSSQL, where I get a summary by days from a range in a table, and this is in union with other queries. This query is used to generate days in a specific range, then add the registry per day, and exclude the registry that are equal to others (in this case, count the rows that tipo is 1, and tipo = 0, and if both are equal, exclude this), and then do a union with a single query.

Is there any way to improve this query?

USE [C:\PROGRAMDATA\REGISFING\REGISFING.MDF];
/* Borre las tablas temporales si existen. */
IF OBJECT_ID('tempdb..#Period') IS NOT NULL DROP TABLE #Period;
IF OBJECT_ID('tempdb..#Registro') IS NOT NULL DROP TABLE #Registro;

DECLARE @FInicio date = '29/02/2016';
DECLARE @FFinaliza date = '04/04/2016';
/* Los siguientes son para utilizar los listados en los filtros */
DECLARE @Cedula table(Ced int);
INSERT @Cedula(Ced) VALUES (1073237901), (1032456940), (1070622582), (45504769);
DECLARE @Puntos table(Punto int);
INSERT @Puntos(Punto) VALUES (0), (43), (99);
/* Importante al pasar al .Net se debe modificar y adjuntar según las elecciones en los controles */

WITH CTE AS
    (SELECT DISTINCT CONVERT(date,Inicio,101) AS StartTime,
            DATEDIFF(dd, Inicio, Finaliza) AS diff, cedula
        FROM Asignaciones
            /* Aquí colocar el codigo para las cedulas específicas */
                WHERE cedula IN (SELECT Ced FROM @Cedula)
UNION ALL
    SELECT StartTime, diff - 1 AS diff, cedula
        FROM CTE
            WHERE diff <> 0)

    SELECT DISTINCT DATEADD(dd, diff, StartTime) AS Dias, C.cedula
        INTO #Period
        FROM CTE C, Asignaciones A
            WHERE C.cedula = A.cedula
                    /* Filtra entre las fechas especificadas */
                    AND (DATEADD(dd, diff, StartTime) BETWEEN @FInicio AND @FFinaliza)
        GROUP BY StartTime, C.cedula, diff--, R.Fecha
        ORDER BY C.Cedula, Dias

SELECT R.cedula, (CAST(Fecha AS date)) AS Dia, Tipo_Reg, COUNT(CAST(R.Fecha AS date)) AS Cantidad
    INTO #Registro
    FROM Registro R
            /* Filtra entre las fechas especificadas */
        WHERE R.Fecha BETWEEN @FInicio AND @FFinaliza
            /* Filtra entre las cedulas especificadas */
            AND cedula IN (SELECT Ced FROM @Cedula)
            /* Filtra entre las ubicaciones especificadas */
            AND (R.IdUbicacion IN (SELECT Punto FROM @Puntos))

GROUP BY R.cedula, (CAST(R.Fecha AS date)), R.Tipo_Reg

/* Se unen las dos consultas temporales */
SELECT 'XX No timbrados' AS column1,
        CONCAT(p.cedula, ' ', U.Nombre, ' ', U.Apellido) AS column2,
        'Diferencias' AS column3,
        CAST(p.Dias AS datetime) AS column4,
        CONCAT('Entradas: ', CASE WHEN SUM(CASE WHEN R.Tipo_Reg = 0 THEN Cantidad END) IS NULL THEN 'No timbró' ELSE CAST(SUM(CASE WHEN R.Tipo_Reg = 0 THEN Cantidad END) AS varchar) END,
            ' - Salidas: ', CASE WHEN SUM(CASE WHEN R.Tipo_Reg = 1 THEN Cantidad END) IS NULL THEN 'No timbró' ELSE CAST(SUM(CASE WHEN R.Tipo_Reg = 1 THEN Cantidad END) AS varchar) END) AS column5
    FROM Usuario U, #Period p
        LEFT JOIN #Registro r on r.cedula = p.cedula AND r.Dia = p.Dias
    WHERE U.cedula = P.cedula
    GROUP BY P.cedula, U.Nombre, U.Apellido, CAST(p.Dias AS datetime)
        HAVING SUM(CASE WHEN R.Tipo_Reg = 0 THEN Cantidad END) IS NULL OR SUM(CASE WHEN R.Tipo_Reg = 1 THEN Cantidad END) IS NULL
                OR SUM(CASE WHEN R.Tipo_Reg = 0 THEN Cantidad END) <> SUM(CASE WHEN R.Tipo_Reg = 1 THEN Cantidad END)

    UNION ALL
SELECT CONCAT(P.IdUbicacion, ' ', P.nombre) AS column1,
        CONCAT(U.cedula, ' ', U.Nombre, ' ', U.Apellido) AS column2,
        (CASE WHEN R.Tipo_Reg = 1 THEN 'Entrada' ELSE 'Salida' END) AS column3,
        N.Fecha AS column4,
        N.Observacion AS column5
    FROM Novedades N, Usuario U, Registro R, Ubicacion P
        WHERE (U.cedula = N.cedula
            AND R.cedula = N.cedula
            AND R.Fecha = N.Fecha
            AND R.IdUbicacion = P.IdUbicacion)
            AND R.Fecha BETWEEN @FInicio AND @FFinaliza

ORDER BY column1, column2, column4


texts: Simple PHP project to store inputs in MySQL and output them

texts:
As my first simple PHP project, I've created a simple project that allows you to just enter your name and two numbers, where it displays them on the page and stores them in a database. It consists of 3 files: index.php, db.php & process.php. I wonder whether I have created the code efficiently.

I'm curious about all the talk behind procedural PHP vs OOP. I initially used some deprecated PHP5 functions and was corrected by the stack overflow community, but this has left me confused as to what specifically I should learn with PHP as a beginner. It sounds like procedural and OOP are very different, and that I should only pick one and learn that.

So my questions are as follows:

Is the coding in my project acceptable?
Is it similar to how most PHP projects are built? (i.e. are most procedural or OOP)
What should I learn as a beginner? (procedural or OOP?)
Do you have any beginner advice?

Any advice here would be very much appreciated as I'm new to PHP. Thanks for any help here. The files and code (excluding HTML & CSS) are below:

index.php:

<?php include 'db.php'; ?>

<?php
// Fetch data from db
$query = mysqli_query($con, 'SELECT * FROM data');
?>

            <?php while ($row = $query->fetch_assoc()) : ?>

<?php echo $row['t_name'] ?> entered <?php echo $row['t_firstNo'] ?> and <?php echo $row['t_secondNo'] ?> (result =
                    <?php
                        $first = $row['t_firstNo'];
                        $second = $row['t_secondNo'];
                        $result = $first * $second;
                        echo $result;
                    ?>)

            <?php endwhile ?>

            <?php if(isset($_GET['error'])) : // if error variable is there ?>
                <?php echo $_GET['error']; // get the error ?>
            <?php endif ?>

db.php:

<?php

// Connect
$con = mysqli_connect("localhost", "tnnick", "PHPprojects", "timesNumbers");

// Test Connection
if (mysqli_connect_errno()) {
    echo 'Failed: '.mysqli_connect_error();
}

?>

process.php:

<?php include 'db.php' ; ?>

<?php
    if(isset($_POST['submit'])) { // if form submitted
        $nickname = mysqli_real_escape_string($con, $_POST['nickname']); // get the inputs
        $firstNo = mysqli_real_escape_string($con, $_POST['firstNo']);
        $secondNo = mysqli_real_escape_string($con, $_POST['secondNo']);
    }
?>

<?php
// validate inputs
if(!isset($nickname) || $nickname=='' || !isset($firstNo) || $firstNo=='' || !isset($secondNo) || $secondNo=='' ) {
    // if invalid input, send error to index.php
    $error = 'Bad input - try again.'; // create error message
    header("Location: index.php?error=".urlencode($error)); // attach to URL & send to index.php
    exit();
} else {
    // insert into DB
    $putIntoDB = "INSERT INTO data (t_name, t_firstNo, t_secondNo) VALUES ('$nickname','$firstNo','$secondNo')";

    // check it inserted
    if(!mysqli_query($con, $putIntoDB)) {
        die('Error');
    } else {
        header("Location: index.php");
        exit();
    }
}
?>


texts: Advice on "Factory" Pattern Implementation

texts:
I'm refactoring some code around a couple of ASP.NET Web Forms pages and decided to try out a variation of the Abstract Factory pattern of my own design. I need to create an implementer of an abstract class based on what query string value is available.

Here's (a simplified version of) what I have right now:

internal static class Factory
{
   public static AbstractClass Create(NameValueCollection queryString)
   {
       if (queryString["class1"] != null)
       {
            return new Class1(queryString["class1"]);
       }
       if (queryString["class2"] != null)
       {
           return new Class2(queryString["class2"]);
       }
       if (queryString["class3"] != null)
       {
           return new Class3(queryString["class3"]);
       }

       return null;
   }
}

I don't know how I feel about this implementation. It certainly is better than what was there before, but I have a strong sense this could be improved some how.

So now, in the relevant pages, I can simply do this:

AbstractClass item = Factory.Create(Request.QueryString);
item.DoStuff();

Does anyone have any suggestions? Or would this be considered good as-is?


texts: has_cycle in directed and undirected graphs

texts:
I wrote a program that can tell if a graph has_cycle or not.

Can you please suggest more elegant and eloquent ways for this program?
(Perhaps better ways to represent a graph with vertices and edges?)

def has_cycle(g, directed=False):
    def dfs(x, entered, exited, tree_edges, back_edges):
        if x not in entered:
            entered.add(x)
            for y in g[x]:
                if y not in entered:
                    tree_edges[y] = x
                elif (not directed and tree_edges.get(x, None) != y
                      or directed and y not in exited):
                          back_edges.setdefault(y, set()).add(x)
                dfs(y, entered, exited, tree_edges, back_edges)
            exited.add(x)
        return (tree_edges, back_edges)
    for x in range(len(g)):
        if dfs(x, entered=set(), exited=set(), tree_edges={}, back_edges={})[1]:
            return True
    else:
        return False

Test Cases - Directed Graphs

'''    A0 →  C2 → E4
graph: ↓  ↗  ↓   ↗
       B1    D3     '''
a, b, c, d, e = range(5)
g = [
    {b, c}, # a
    {c},    # b
    {d, e}, # c
    {e},    # d
    set()   # e
]

assert not has_cycle(g, True)

g[a] = {b}
g[c] = {a, d, e}
assert has_cycle(g, True)

Test Cases - Directed Graphs

# undirected graph: A0 - B1 - C2
a, b, c = range(3)
g2 = [
    {b},    # a
    {a, c}, # b
    {b}     # c
]
assert not has_cycle(g2, False)

# undirected graph: A0 - B1 - C2 - A0
g2[a].add(c)
g2[c].add(a)
assert has_cycle(g2, False)


texts: Jasmine unit test that triggers mouse events in Angular 4

texts:
I have the following jasmine test spec which triggers the mouse events in my directive. As you can see there is a lot of code duplication here, I am repeating the events here.

describe('Test for my module', () => {
        let fixture: ComponentFixture<TestComponent>;
        let de: DebugElement[];
        let service: MyService = new MyService();

        beforeEach(() => {
            TestBed.configureTestingModule({
                declarations: [Move, TestComponent],
                providers: [MyService]
            });
            fixture = TestBed.createComponent(TestComponent);
            service = fixture.debugElement.injector.get(MyService);
            fixture.detectChanges();
            de = fixture.debugElement.queryAll(By.directive(Move));
        });

// My test spec. This is where I need advice for removing the code duplication.
it('test the move event', inject([MyService], (service: MyService) => {
                let object = spyOn(service.x, 'emit');
                spyObj.and.callThrough();
                de[0].triggerEventHandler('mousedown', { pageX: 10, pageY: 10 });
                de[0].triggerEventHandler('mousemove', { pageX: 40, pageY: 20 });
                expect(service.x.emit).toHaveBeenCalledWith({ x: 30, y: 10 });
                object.calls.reset();
                de[0].triggerEventHandler('mousemove', { pageX: 45, pageY: 25 });
                expect(service.x.emit).toHaveBeenCalledWith({ x: 35, y: 15 });
                object.calls.reset();
                de[0].triggerEventHandler('mousemove', { pageX: 50, pageY: 30 });
                expect(service.x.emit).toHaveBeenCalledWith({ x: 40, y: 20 });

            }));

Could anyone help me by suggesting any way to avoid this duplication?


texts:
This code is for the penalized logistic regression that we should to choose  \$\lambda\$ in regularization to control the trade off. I use the first function to estimate the \$\hat{\beta}\$ and the main code is to choose the best \$\lambda\$ by using cross validation leave one out method.

This code takes a really long time. Can anyone help to make it faster?

NRfit.Ridge <- function(y,X,start,lambda,n.iter=30,tol=1e-4,verbose=TRUE) {
## used X rather than Z just because it's more standard notation
n.pred <- ncol(X)
II=matrix(0,nrow=ncol(X),ncol=ncol(X))
diag(II)<-1
B <-  matrix(NA,ncol=n.iter,nrow=n.pred)
B[,1] <- start
for (i in 2:n.iter) {
if (verbose) cat(i,"\n")
p <- plogis(X %*% B[,i-1])
v <- diag(c(p*(1-p)))
score=t(X)%*%(y-p)-B[,i-1]*lambda
increm=solve(t(X)%*%v%*%X+lambda*II)
B[,i]=B[,i-1]-incream%*%score
if (all(abs(B[,i]-B[,i-1]) < tol))
  return(B)
 }
 print(B)
 }

 ####################################################################################
 ############################## The Main Code #######################################

PE=c()
lambda=c(0.005,0.001,0.1,0.5,0.2)

for(j in 1:length(lambda)){
print(lambda[j])
tem.PE=c()
for(i in 1:2014){
cv.y=y[-i]
cv.x=x[-i,]
tem.lambda=lambda[j]
fit=NRfit.Ridge(y,X,start=0,lambda=tem.lambda)
fitted=(exp(X%*%fit[,30]))/(1+exp(X%*%fit[,30]))
f.hat=fitted
 #   print(f.hat)
tem.PE[i]=mean(cv.y-f.hat)
rm(cv.y,cv.x,fit,f.hat,tem.lambda)
 }
PE[j]=mean(tem.PE)
rm(tem.PE)
}


texts: Add classes onclick and then remove them with onfocus event

texts:
Right now I'm mixing JS and jQuery. I would like to find one unique solution with JS only possibly.

How can I organize the code according to best code practices?

Another thing I need to add is a check at the beginning of the function. If the classes are there nothing should happen, if not there then add them just as below.

function changeClass() {
    document.getElementById("message").className += " dropzone-wrap";
    document.getElementById("dragNdrop").className += " dropzone-content";
}

window.onload = function() {
    document.getElementById("ToggleTxTDrop").addEventListener( 'click' , changeClass );
}

/* lets remove the previous classes when on focus */
$('#message').on('focus', function(){
    $(this).removeClass('dropzone-wrap');
    $(this).parent().removeClass('dropzone-content');
})


texts: Counting Increasing Subsequences of size K recursive

texts:
The original description of the problem can be found here, its input here and its expected output here.

The problem:

  Given a integer sequence a1 ... an (-10000
  \$\leq\$ ai \$\leq\$ 10000). Where n (1 \$\leq\$ n
  \$\leq\$ 100),the size of the sequence, is a given number.

  Find the number of increasing subsequences with length equals to a
  given size k (1 \$\leq\$ k \$\leq\$ n \$\leq\$ 100).

  An increasing subsequence ai1 ... aix of a
  sequence a1 ... an is defined as
  aix-1, \$<\$ aix for all 1 \$<\$ x \$\leq\$ n).

  The input has several testcases. The first line contains the numbers
  n and k. The second line contains a sequence of length n.  0 0 ends the input. The sequence will be given in a way that the
  subsequences count can't be bigger than a signed number of 64 bits.

  Example:

10 5
1 2 3 4 5 6 7 8 9 10
3 2
3 2 1
0 0

  The output is the number of increasing subsequences:

  Example for the above input:

252
0

My solution uses a recursive idea. The sequence values are stored in an array of size n+1 with a \$-\infty\$ in the 0 index of the array. After this, a function goes from de 0 index to de n position recursively. And a comparison is made to check if the current value (picked) is less than the next value.

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

long long memoization[102][102];

long long LCIS(int *S,int len,int picked,int LCISlen, int K){
    if(memoization[picked][LCISlen])
        return memoization[picked][LCISlen];

    long long q = 0;

    int i;
    for (i = picked + 1; i < len; i++) {
        if(S[picked] < S[i] && LCISlen < K)
            q += LCIS(S, len, i, LCISlen + 1, K);
        else if(S[picked] < S[i] && LCISlen == K)
            q++;
    }

    return memoization[picked][LCISlen] = q;
}

int main(){

    int N,K;
    while(scanf("%d %d",&N,&K), (N != 0) && (K != 0)){

        int i, S[N+1];

        S[0] = INT_MIN;

        for (i = 1; i <= N; i++)
            scanf("%d",&S[i]);

        memset(memoization,0,sizeof memoization);

        printf("%lld\n",LCIS(S,N+1,0,1,K));
    }
}

The solution got accepted by the judge, but it takes nearly 1 sec to give the answer. Other solutions take 0 seconds. This made me think that this solution isn't a good one.


texts: Kattis Challenge - Animal Classification

texts:
I'm new to competitive programming and C++ in general.  I have solved the Kattis Animal Classification challenge.  We are given two classification trees, each represented using nested parentheses.  For example, ((3,(1,(5,2))),4) and (((5,1),(2,3)),4) represent the trees

   ╱╲                   ╱╲
  ╱╲ 4                 ╱╲ 4
 ╱ ╱╲                 ╱  ╲
3 1 ╱╲               ╱╲  ╱╲
   5  2             5 1  2 3

The challenge is to report the fact that there are 7 subgroups in common between the two trees (namely {1}, {2}, {3}, {4}, {5}, {1,2,3,5}, and {1,2,3,4,5}).

My approach is to parse the input string [ e.g. ((3,(1,(5,2))),4) ] into a list [ ((3(1(52)))4) ]. After that I note all elements, split it into the two subtrees and add both back to a queue, starting over again, until there is nothing to split anymore. Afterwards i compare the two sets i obtained this way. If i am not mistaken this should lead to a complexity of O(N log(N)), since for every subtree, i need to collect all elements that belong to it, which would amount to N log(N) in a complete binary tree. This works for the provided test sets, but exceeds the time limit on the submission.

Could you please help me figure out where I can improve my code and what I did inefficiently?

#include <iostream>
#include <list>
#include <algorithm>
#include <string>
#include <unordered_set>
#include <deque>

using namespace std;

struct hash_X{
  size_t operator()(const unordered_set<int> &x) const{
    int sum = 0;
    for(int i: x){sum = sum+i;}
    return sum;
  }
};

unordered_set<unordered_set<int>, hash_X> mt(list<string> L){
    unordered_set<unordered_set<int>, hash_X> S;
    list<string> K;
    deque<list<string>> Q;
    Q.push_back(L);
    while(not Q.empty()){
    K = Q.back();
    unordered_set<int> tmp;
    for(string s: K){if( s!="(" and s!=")" ){int i = stoi(s); tmp.insert(i);}}
    S.insert(tmp);
    //K is of the form for example (x(yz)), so first we unwrap ~ x(yz) and split into the two subtrees x and (yz)
    //and add both to the queue. If only one node is left ( x ) we dont add it back to the queue
    if(K.size() >= 2){
        K.pop_front();
        K.pop_back();
        list<string>::iterator it = K.begin();
        if(*it == "("){
            int i = 1;
            while(i != 0){
                it++;
                if(*it == ")"){i = i-1;}
                else if(*it == "("){i=i+1;}
                }
            }
        it++;
        list<string> B;
        list<string>::iterator itB = B.begin();
        B.splice(itB, K, it, K.end());
        Q.push_front(K);
        Q.push_front(B);
    }
    Q.pop_back();
    }
    return S;
}

int main(){
    int n;
    string x, y;
    char c;
    list<string> A, B;
    cin >> n;
    cin.ignore();
    cin >> x;
    cin >> y;
    // parse "((3,(1,(5,2))),4)" into ((3(1(52)))4)
    for(int i = 0; i < x.size(); i++){
    string c = "";
    c += x[i];
    if( c == "(" or c == ")" ){A.push_back(c);}
    if( isdigit(x[i]) ){
        string tmp = "";
        while( isdigit(x[i]) ){
            tmp += x[i];
            i++;
        }
        i--;
        A.push_back(tmp);
    }
    }
    for(int i = 0; i <= y.size(); i++){
    string c = "";
    c += y[i];
    if( c == "(" or c == ")" ){B.push_back(c);}
    if( isdigit(y[i]) ){
        string tmp = "";
        while( isdigit(y[i]) ){
            tmp += y[i];
            i++;
        }
        i--;
        B.push_back(tmp);
    }
    }

    // make the trees
    unordered_set<unordered_set<int>, hash_X> t1 = mt(A);
    unordered_set<unordered_set<int>, hash_X> t2 = mt(B);
    unordered_set<unordered_set<int>, hash_X> i(t1.begin(), t1.end());
    int res = count_if(t2.begin(), t2.end(), [&](unordered_set<int> k) {return i.find(k) != i.end();});
    cout << res;
}