texts: Implementing RSA-AES encryption protocol

texts:
I am trying to write a simple program that allows to encrypt a string of plaintext so that it can be transmitted via an "insecure channel" by which I mean a "regular chat"; be it Skype, Facebook, or even email or something similar. This is what I came up with:

At first, one user, Alice, will generate a cryptographically secure key for this "session" (which can - I think - be very long, so long as new IVs can be generated). It will be used for the AES algorithm.

byte[] sessionKey = GenerateNewKey();

I/You don't need to worry about GenerateNewKey().

This key needs to be transferred. RSA should be used as the asymmetric encryption algorithm. At first, Bob will extract a new private-public Key set RSAParameters from a RSACryptoServiceProvider . Furthermore, I will take the public key as MyPublicKey from that RSAParameters.

RSAParameters extractedParameters;
using (RSACryptoServiceProvider prov = new RSACryptoServiceProvider(
    RsaKeyLength /* const, >= 4096  */)
{
     try
     {
          extractedParameters = prov.ExportParameters(true);
     }
     finally
     {
          prov.PersistKeyInCsp = false;
     }
}
byte[] bobsPublicKey = extractedParameters.Modulus;

Now, this byte[] bobsPublicKey will be given to Alice, by writing it into the chat. She will encrypt the byte[] sessionKey as follows:

byte[] encryptedAES;
using (RSACryptoServiceProvider prov = new RSACryptoServiceProvider())
{
    try
    {
        prov.PersistKeyInCsp = false;
        RSAParameters param = prov.ExportParameters(false);
        param.Modulus = bobsPublicKey;
        prov.ImportParameters(param);
        prov.PersistKeyInCsp = false;
        encryptedAES = prov.Encrypt(sessionKey, true /* use OAEP */);
    }
    finally
    {
        prov.PersistKeyInCsp = false;
    }
}

Then, she will write encryptedAES into the chat, which will be received by Bob, who finally gets the AES key sessionKey back via:

byte[] sessionKey;
using (RSACryptoServiceProvider prov = new RSACryptoServiceProvider())
{
    try
    {
        prov.PersistKeyInCsp = false;
        prov.ImportParameters(extractedParameters);
        prov.PersistKeyInCsp = false;
        sessionKey = prov.Decrypt(encryptedAES, true /* use OAEP */);
    }
    finally
    {
        prov.PersistKeyInCsp = false;
    }
}

Now, lets say Alice wants to send a message to Bob. Assume that for example _aes = "AES, 256 key, CBC, PKCS7"

byte[] iv = GenerateIV(8 /*byte length*/);
byte[] encryptedMessage;
using (MemoryStream ms = new MemoryStream())
{
     ms.Write(iv, 0, iv.Length); // Prepend the IV to the Stream
     // Append the encrypted message
     using (ICryptoTransform trans = _aes.CreateEncryptor(sessionKey, iv))
     using (CryptoStream cs = new CryptoStream(ms, trans, CryptoStreamMode.Write)
     using (StreamWriter sw = new StreamWriter(cs))
     {
         sw.Write(message);
         sw.Flush();
         cs.FlushFinalBlock();
     }
     encryptedMessage = ms.ToArray();
}

encryptedMessage will be written to the chat. Bob decypts like:

// extract the IV
byte[] iv = GetIV(encryptedMessage);
// the rest will be the actual message
byte[] data = GetData(encryptedMessage); // Don't worry about those two

byte[] decryptedMessage;
using (MemoryStream ms = new MemoryStream(data, iv.Length, 0))
using (ICryptoTransform trans = _aes.CreateDecryptor(sessionKey, iv))
using (CryptoStream cs = new CryptoStream(ms, trans, CryptoStreamMode.Read)
using (StreamReader sr = new StreamReader(cs))
    decryptedMessage = sr.ReadToEnd();

And finally, decryptedMessage should contain the message Alice tried to send.

My request is, that this code should be reviewed regarding

whether this is a correct - that is secure - implementation of such an "algorithm pair" for transmitting messages via an unsafe and permanently visible channel
whether there are redundant calls to the .Net classes
(more things that can be improved regarding the first point)


texts: Module with helper functions to initialize or reinitialize a Slick carousel

texts:
I been getting into javascript patterns and would love to get some feedback. I notice that I got some general helper functions. Is this a good approach of dealing with it?

// carousel.js

var Carousel = (function() {
  var timeout = 340;

  function init() {
    applyForTheseQueries();

    $(window).on('resize', Helpers.debounce(function() {
      applyForTheseQueries();
    }, timeout));
  }

  function applyForTheseQueries() {
    var $carousel = $('.js-slick');
    var query = $carousel.data('query');
    var mediaQuery = Helpers.executeFunctionByName(query, window);

    if (mediaQuery && !$carousel.hasClass('init-done')) {
      $carousel.addClass('init-done').slick();
    } else if (!mediaQuery && $carousel.hasClass('init-done')) {
      $carousel.removeClass('init-done').slick('unslick');
    }
  }

  return {
    init: init
  };
})();

$(function() {
  Carousel.init();
});

// helpers.js

var Helpers = (function() {
  function executeFunctionByName(functionName, context) {
    var args = [].slice.call(arguments).splice(2);
    var namespaces = functionName.split(".");
    var func = namespaces.pop();

    for (var i = 0; i < namespaces.length; i++) {
      context = context[namespaces[i]];
    }

    return context[func].apply(context, args);
  }

  function debounce(func, wait, immediate) {
    var timeout;
    return function() {
      var context = this;
      var args = arguments;

      var later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
      };

      var callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);

      if (callNow) func.apply(context, args);
    };
  };

  return {
    executeFunctionByName: executeFunctionByName,
    debounce: debounce
  };
})();


texts:
I am preparing for technical interview and I found this question on geeksforgeeks, but I did not understand their solution. So, I have written my own solution. I want to optimize this code.

#include <iostream>
#include <string>

bool isPalindrome(std::string& str)
{
    for (int i = 0, j = str.length()-1; i<j; ++i, --j)
    {
        if (str[i] != str[j])
        {
            return false;
        }
    }
    return true;
}

int longestPalindrome(std::string& str, std::string& palindromeStr)
{
    int max = 0, start = 0, end = 0;
    for (int i = 0; i < str.length(); ++i)
    {
        for (int j = i+1; j < str.length(); ++j)
        {
            std::string sub = str.substr(i, j);
            if (isPalindrome(sub) && max < sub.length())
            {
                max = sub.length();
                start = i;
                end = j;
            }
        }
    }
    palindromeStr = str.substr(start, end);
    return max;
}

int main()
{
    std::string str = "forgeekskeegfor";
    std::string palindromeStr;
    std::cout << longestPalindrome(str, palindromeStr) << '\n';
    std::cout << palindromeStr << '\n';
}


texts:
I am quite new to JavaScript and I wonder if you experts can see any obvious mistakes in this working code, and if any, suggest good improvements.

// add iframes to page
var normal_sortables = document.getElementById('normal-sortables');
normal_sortables.innerHTML = normal_sortables.innerHTML + '

';

// declaring all variables
var code_to_be_inserted = '',
textarea_content = document.getElementById('content'),
iframe_upload = document.getElementById('iframe_upload'),
iframe_images = document.getElementById('iframe_images'),
iframe_pdf_documents = document.getElementById('iframe_pdf_documents');

// upload iframes of images and pdf documents when file is uploaded
iframe_upload.onload = function () {
iframe_images.src = 'images.php';
iframe_pdf_documents.src = 'pdf.php';
}

// add image to content editor
iframe_images.onload = function () {
    var images = iframe_images.contentWindow.document.getElementsByTagName('img');
    for (var i = 0; i < images.length; i++) {
        images[i].onclick = function () {
            code_to_be_inserted = '\n\n';
            textarea_content.value = code_to_be_inserted + textarea_content.value;
        }
    }
}

// add pdf documents to content editor
iframe_pdf_documents.onload = function () {
    var pdf_documents = iframe_pdf_documents.contentWindow.document.getElementsByTagName('a');
    for (var i = 0; i < pdf_documents.length; i++) {
        pdf_documents[i].onclick = function () {
            code_to_be_inserted = '\n\nClick here to open ' + this.innerHTML + '';
            textarea_content.value = textarea_content.value + code_to_be_inserted;
            alert ('testar');
            return false;
        }
    }
}


texts: Password Manager UI: Populating DataGridView is Painfully Slow

texts:
I'm designing a small account/password manager using C# and SQL Server CE. LINQ to SQL is my ORM of choice.

Here's the data model representing how the SQL Server CE database is set up:

And here's my GUI with a cheesy color-coding system to show how the data is mapped to the GUI:

Since the user is able to dynamically add whatever fields and columns they want, I can't simply bind the DataGridView to a table or collection. Instead, the DataGridView's columns, rows, and cells each have to be populated separately and manually.

Below is my implementation. It gets the job done, but it's TERRIBLY SLOW! We're talking 5-6 seconds to populate the DataGridView with only 10 accounts and 10 fields. The implementation just feels clunky. I've considered creating a DataTable and binding that to the DataGridView, but I would still have to manually populate the columns and rows, and it would be harder without the Tag property to identify columns, rows, and cells. Any suggestions to improve anything ranging from my database design to my GUI are welcome!

Business Logic Methods

    public static List<Account> GetAccountsByCategory(int categoryID)
    {
        using (PassShedEntities context = new PassShedEntities())
        {
            return context.Account.Where(a => a.Category_id == categoryID).OrderBy(a => a.Id).ToList();
        }
    }

    public static Credential GetCredential(int accountID, int fieldID)
    {
        using (PassShedEntities context = new PassShedEntities())
        {
            return (from c in context.Credential
                    join f in context.Field on c.Field_id equals f.Id
                    join a in context.Account on c.Account_id equals a.Id
                    where c.Account_id == accountID
                    where f.Id == fieldID
                    select c).SingleOrDefault();
        }
    }

    public static List<Field> GetFieldsByCategoryID(int categoryID)
    {
        using (PassShedEntities context = new PassShedEntities())
        {
            return context.Field.Where(f => f.Category_id == categoryID).OrderBy(f => f.Display_index).ToList();
        }
    }

Populate Fields (DataGridView Columns)

    private void PopulateFields(int categoryID)
    {
        dgvShed.Columns.Clear();

        foreach (Field field in FieldLogic.GetFieldsByCategoryID(categoryID))
        {
            DataGridViewColumn fieldColumn = new DataGridViewTextBoxColumn();
            fieldColumn.Name = field.Label;
            fieldColumn.HeaderText = field.Label;
            fieldColumn.Tag = field.Id;

            if (field.Display_index != null)
            {
                fieldColumn.DisplayIndex = (int)field.Display_index;
            }

            dgvShed.Columns.Add(fieldColumn);
        }
    }

Populate Accounts (DataGridView Rows)

    private void PopulateAccounts(int categoryID)
    {
        dgvShed.Rows.Clear();

        foreach (Account account in AccountLogic.GetAccountsByCategory(categoryID))
        {
            DataGridViewRow accountRow = new DataGridViewRow();
            accountRow.Tag = account.Id;

            foreach (DataGridViewColumn column in dgvShed.Columns)
            {
                Credential credential = CredentialLogic.GetCredential(account.Id, (int)column.Tag);

                DataGridViewTextBoxCell credCell = new DataGridViewTextBoxCell();
                credCell.Tag = credential.Id;
                credCell.Value = credential.Value;

                accountRow.Cells.Add(credCell);
            }

            dgvShed.Rows.Add(accountRow);
        }
    }


texts: Optimise runtime of filter character method

texts:
I'm trying to run the method below against a very large corpus and I need to optimize/reduce the run time for this method as it already takes up about 6 seconds to execute.

Requirements:

Check the word only consist of alphabets, hyphen and apostrophe
First character of word must be alphabet
Last character of word must be alphabet or apostrophe only
Use of re library (regex) strictly not allowed

def delUnknownChar(w):
    wf = []
    for c in w:
        if (c == "'" or c == "-" or c.isalpha()):
            wf.append(c)

    w = "".join(wf)
    wf.clear()

    if (len(w) > 1):
        while(not w[0].isalpha()):
            w = w[1:]

        while (w[-1] == "-"):
            w = w[:-1]

        return w
    else:
        return None

string1 = delUnknownChar("-'test'-")
print(string1)

Output will be test'
The code above will take about 5 seconds to run.

If I change lines 2-7 of the code to this line:

w = "".join(c for c in w if c == "'" or c == "-" or c.isalpha())

The runtime somehow increases by 1 more second.

Does anyone here have a better idea or an improved optimized way to check for this at a much faster speed?


texts:
I was playing with TCP/IP, and came across this 16 bit checksum function:

unsigned short csum(unsigned short *ptr,int nbytes)
{
    register long sum;
    unsigned short oddbyte;
    register short answer;

    sum=0;
    while(nbytes>1) {
        sum+=*ptr++;
        nbytes-=2;
    }
    if(nbytes==1) {
        oddbyte=0;
        *((u_char*)&oddbyte)=*(u_char*)ptr;
        sum+=oddbyte;
    }

    sum = (sum>>16)+(sum & 0xffff);
    sum = sum + (sum>>16);
    answer=(short)~sum;

    return(answer);
}

There were a few things that bothered me about it:

Not using fixed size types (though the author himself stated in the code short was expected to be 16 bits for it to work)
If the input buffer was too large (I believe larger than exactly 65535 bytes) the checksum wouldn't be correct, since the most significant 2 bytes of the checksum variable would overflow.

So I ended up rewriting it:

uint16_t checksum16(void *data, unsigned int bytes){
    uint16_t *data_pointer = (uint16_t *) data;
    uint32_t total_sum;

    while(bytes > 1){
        total_sum += *data_pointer++;
        //If it overflows to the MSBs add it straight away
        if(total_sum >> 16){
            total_sum = (total_sum >> 16) + (total_sum & 0x0000FFFF);
        }
        bytes -= 2; //Consumed 2 bytes
    }
    if(1 == bytes){
        //Add the last byte
        total_sum += *(((uint8_t *) data_pointer) + 1);
        //If it overflows to the MSBs add it straight away
        if(total_sum >> 16){
            total_sum = (total_sum >> 16) + (total_sum & 0x0000FFFF);
        }
        bytes -= 1;
    }

    return (~((uint16_t) total_sum));
}

Since it adds the carry bit right after the sum, you can feed it with a buffer of any size with no worries of the final checksum being incorrect.

After some small tests, the results seem to be matching. Do you guys see any possible bug while using that function? Or any further improvement?

I thought maybe I could add a statement to check if the number of bytes was larger than 65535, and only add the carry on each iteration if it was, otherwise adding the whole sum of carries at the end. That would improve the performance on the cases where the size of the buffer doesn't reach that limit (true to any IP packet, since the header length field is 16 bits, limiting the packet size to 65535).


texts:
I'm looking for a better way to manage employee photos for employee records in our database, and a way to query for the employee photos while having them on disk I have used a FileTable to store all the EmployeePhotos.

Then in my Employee View I created a join using substring, which I am concerned about. I am wondering if there is a better way of doing this.

Here's the View:

CREATE VIEW [emp].[ViewEmployees]
    AS SELECT
        ue.Id,
        ue.Active,
        ue.Comments,
        ue.Created,
        ue.IsLockedOut,
        ue.LastLoggedOn,
        ue.NameIdentifier,
        e.FirstName,
        e.MiddleName,
        e.LastName,
        e.DisplayName,
        e.Duties,
        e.EmailAddress,
        e.FullPart,
        e.JobTitle,
        e.LegacyId,
        e.OtherPhones,
        e.Phone,
        e.Profile,
        e.StartDate,
        e.ShowOnDirectories,
        ep.name as PhotoName,
        ep.file_stream as PhotoBytes
        FROM [security].[UserEntity] as ue
Full Join [emp].[Employees] as e on ue.Id = e.Id Left Outer Join emp.EmployeePhotos as ep on SUBSTRING(e.EmailAddress, 0, CHARINDEX('@', e.EmailAddress, 0)) = SUBSTRING (ep.name, 0, CHARINDEX('.', ep.name, 0)) where ue.UserEntityType = 0

When you add files to the folder, it automatically creates a record in the file table with a new guid.  We want to allow administrators access to that folder as a network share so they can drop new employee photos in it, or edit them.  As such I can't really think of a better way to join it on my employee view.

Or maybe I shouldn't have it in the view at all, and instead do a separate query in the application to the file table for the photo.


texts:
I echo a rank of a student whose regd is equal to $regd. In fact, this is working code. However, I was advised by a friend that the MySQL statements Distinct and Group By should not be used together. But as a newbie, I could not figure out how I could implement it without using Distinct because it does not return rows without Distinct.

Can anyone suggest how I can improve this code?

<?php
mysql_select_db($database_dbconnect, $dbconnect);
$query_myrank = "SELECT Distinct regd, Name_of_exam,
                    Name_of_Student, TOTALSCORE, Rank
             FROM (SELECT *, IF(@marks = (@marks := TOTALSCORE),
                          @auto, @auto := @auto + 1) AS Rank
                   FROM (SELECT Name_of_Student, regd,
                               Name_of_exam, SUM(Mark_score) AS TOTALSCORE
                         FROM cixexam, (SELECT @auto := 0,
                                               @marks := 0) AS init
                                        GROUP BY regd
                         ORDER BY TOTALSCORE DESC) t) AS result
             HAVING (Name_of_exam='First Terminal Exam' OR
                     Name_of_exam='First Term Test')";

$myrank = mysql_query($query_myrank, $dbconnect) or die(mysql_error());

$i = 0;
$j = 0;
$data = array();
while($row_myrank = mysql_fetch_assoc($myrank))
{
   $data[$i] = $row_myrank;
   if(isset($data[$i - 1])
        && $data[$i - 1]['TOTALSCORE'] == $data[$i]['TOTALSCORE'])
{
   $data[$i]['Rank'] = $j;
   }else{
     $data[$i]['Rank'] = ++$j;
}
   $i++;
}
foreach($data as $key => $value)
{
 if($value['regd'] == $regd)
    {
    echo $value['Rank'];
    }
  }
 ?>


texts: Generate sample coordinates inside a Polygon

texts:
I have a Polygon named as poly. I attempted to randomly select 5 coordinate points that lies inside the polygon.

import numpy as np
from shapely.geometry import Polygon, Point

poly = Polygon([(141.4378366,-25.95915986), (165.4279876,-29.43400298), (163.1382942,-47.65345814), (133.1675418,-42.99807751)])

minx, miny, maxx, maxy = poly.bounds

longs = np.arange(minx, maxx, 0.002); lats = np.arange(miny, maxy, 0.002)
longs = np.tile(longs,3).ravel(); lats = np.repeat(lats,3).ravel()
coords = np.array([(x,y) for x,y in zip(longs,lats)])

points = [Point(xy) for xy in coords]

check = [xy.within(poly) for xy in points]
pointsInside = coords[check]

ranIdx = np.random.choice(len(pointsInside),5,replace=False)
result = pointsInside[ranIdx]

print result

I think my code is ineffective. Are there any ideas for a straight and elegant implementation?


texts: TPL Task tracker which keeps track of tasks

texts:
This class keeps track of tasks which are added and tries to remove them after certain delay. I tried doing it with CustomTaskScheduler but didn't get much in return.

Here is my related question on SO.

I would be glad to know if there are other ways to track tasks.

public class TaskCompletedNotifier
{
    public delegate void AllTasksCompletedHandler(object sender);
    public delegate void TaskStartedHandler();
    public event AllTasksCompletedHandler AllTasksCompleted;
    public event TaskStartedHandler TaskStarted;

    private object syncLock = new object();
    private SynchronizedCollection<Task> tasksCollection;
    private bool isTaskStartedNotified;
    private readonly uint delay;

    public TaskCompletedNotifier(uint delayBeforeRemovingTasks)
    {
        tasksCollection = new SynchronizedCollection<Task>();
        delay = delayBeforeRemovingTasks;
    }

    public void Add(Task task)
    {

        if (!isTaskStartedNotified)
        {
            isTaskStartedNotified = true;
            TaskStarted?.Invoke();
        }

        task.ContinueWith(t =>
        {
            RemoveTask(t);
        });

        tasksCollection.Add(task);
    }

    private async void RemoveTask(Task task)
    {
        await Task.Delay(300);
        await Task.Run(() =>
        {
            tasksCollection.Remove(task);

            if (tasksCollection.Count == 0)
            {
                isTaskStartedNotified = false;
                AllTasksCompleted?.Invoke(tasksCollection);
            }
        });
    }
}


texts: Creating a visual pattern of a text file

texts:
I made a Python script that takes an input text file in binary (1 character at each line) and creates a visual pattern with it, as an image, but I need to know if there are better solutions to my methods and what can I do to optimize it.

What it does is it takes the text file, put every line in an array, create a square image based on the array length and draw each pixel of the image based on the elements of the array as either black or white, being black if the element is 0 and white if it's 1.

import math
from PIL import Image
import easygui as gui
import sys
def replace_last(source_string, replace_what, replace_with):
    head, _sep, tail = source_string.rpartition(replace_what)
    return head + replace_with + tail

def str2tupleList(s):
    return eval( "[%s]" % s )

t = gui.buttonbox("BinaryToPadronizedVisualCode", "BinaryToPadronizedVisualCode",["Select File", "Exit"])
if t =="Select File":
 fs = gui.fileopenbox()
 fs
else:
 sys.exit()

with open(fs, 'r') as f:
 Bin = [line.strip() for line in f]

half = int(round(math.sqrt(len(Bin))))
im = Image.new('RGB', (half, half+1))

imagem = ""
num = 0
while (num<len(Bin)):
  Bin[num]
  if Bin[num] == "0":
    b = "0, 0, 0"
  else:
    b = "255, 255, 255"
  imagem = (imagem + "(" + b + "), ")
  num += 1

imagem = replace_last(imagem, ', ', "")

im.putdata(str2tupleList(imagem))

imm = im.resize((1000,1000))
imm.save('bintoimg.jpg')
gui.msgbox("Image Saved!")


texts:
A bowling score calculator is my go-to exercise for learning the basics of a language. I recently had to pick up Perl so I did this.

I'm concerned that I'm doing subroutines wrong. I had a hard time figuring out the syntax for dealing with arguments and what exactly @_ is.

I'm just looking for feedback on any egregious mistakes or instances where I go against convention.

use strict;
use warnings;
use List::Util qw(sum);

sub is_strike { #is this frame a strike?
    $_[0] == 10;
}

sub is_spare { #is this frame a spare?
    ($_[0] + $_[1]) == 10;
}

sub throws_for_score { #how many extra throws contribute to this frame's score?
    (is_strike(@_) || is_spare(@_)) ? 2 : 1;
}

sub frame_advance { #how many throws should we consume to move to the next frame?
    is_strike(@_) ? 1 : 2;
}

sub score_frame { #sum the score for x throws, where x is the number of throws that count for this frame's score
    my $frame_index = $_[1];
    my $frame_end = $frame_index + 2;
    my $score_end = $frame_index + throws_for_score(@{$_[0]}[$frame_index..$frame_end]);
    sum @{$_[0]}[$frame_index..$score_end];
}

sub score_game {
    (my $game = $_[0]) =~ s/-//gi; #remove hyphens
    my @throws = split(//, $game); #create an array of throws
    find_strikes(\@throws);
    my $current = 0;
    my $score = 0;
    do {
        my $frame_score = score_frame(\@throws, $current);
        $score += $frame_score;
        $current += frame_advance(@throws[$current..($current+2)]);
    } while($current <= $#throws-2); #while the current index is not beyond the tenth frame
    $score;
}

sub find_strikes { #replace strike marks with 10
    foreach(@{$_[0]}) {
        if($_ eq 'X') {
            $_ = 10;
        }
    }
}

print score_game("X-X-X-X-X-X-X-X-X-X-XX") . "\n"; #300
print score_game("55-55-55-55-55-55-55-55-55-55-5") . "\n"; #150
print score_game("00-00-00-00-00-00-00-00-X-X-XX"); #60


texts: Connected components algorithm does not scale past 10,000 nodes

texts:
I found a connected components algorithm posted here on SO and modified it for my own purposes. It runs well for small input sets, but doesn't scale as well as I would like.

The largest set I've been able to handle with it has just under 10,000 nodes and took 109 seconds to process. I threw in the towel when testing a set of about 107,000 nodes after 30 minutes at 100% CPU load (RAM utilization <10%).

I have several sets in the 100,000- to 300,000-node range in which I'd like to identify connected components. Is there some way I could modify this algorithm to scale better?

Node = collections.namedtuple('Node', 'fact_id person_ids names')

def grouped(neighborhood):
    """takes a flat set of nodes and returns the connected subsets"""
    seen = set()
    def component(node):
        unseen_nodes = set((node,))
        while unseen_nodes:
            node = unseen_nodes.pop()
            seen.add(node)
            unseen_nodes |= adjacent(node, neighborhood) - seen
            yield node
    return (set(component(node)) for node in neighborhood if node not in seen)

def adjacent(a, n):
    """returns all elements of n(eighborhood) adjacent to a(ctive node)"""
    return {e for e in n if a.person_ids & e.person_ids or a.names & e.names}

My background is not in computer science but I'm willing to take some time to study and understand an alternative approach, within reason.

I can't provide my source data but here's set of example Nodes comprising four connected components, if that's helpful:

examples = set([
    Node(49559, frozenset(['62169']), frozenset(['COX'])),
    Node(56669, frozenset(['62169', '70260']), frozenset(['COX', 'HUGHES'])),
    Node(71440, frozenset(['87830', '87829']), frozenset(['WARREN'])),
    Node(267031, frozenset(['303253']), frozenset(['FOX'])),
    Node(324771, frozenset(['358566']), frozenset(['FOX'])),
    Node(405519, frozenset(['427822']), frozenset(['EVANS'])),
    Node(437153, frozenset(['452540', '452541']), frozenset(['BOYD'])),
    Node(474774, frozenset(['482316']), frozenset(['WARREN'])),
    Node(509974, frozenset(['509895', '509894']), frozenset(['BOYD'])),
    Node(552313, frozenset(['544087', '544086']), frozenset(['BOYD'])),
    Node(566768, frozenset(['555467', '555468']), frozenset(['GARDNER', 'WARREN'])),
    Node(603318, frozenset(['583882', '583883']), frozenset(['WARREN'])),
    Node(886519, frozenset(['891668']), frozenset(['FOX'])),
    Node(951212, frozenset(['973755', '973754']), frozenset(['COX'])),
    Node(1043850, frozenset(['1090122']), frozenset(['GARDNER'])),
    Node(1136082, frozenset(['1204393', '1204394']), frozenset(['WILSON', 'BOYD'])),
    Node(28161119, frozenset(['1204393']), frozenset(['WILSON'])),
    Node(1343476, frozenset(['973755', '973754']), frozenset(['COX'])),
    Node(1347042, frozenset(['1457174']), frozenset(['BOYD'])),
    Node(1469345, frozenset(['1597595']), frozenset(['GARDNER'])),
    Node(1561624, frozenset(['1701196', '1701195']), frozenset(['GARDNER', 'EVANS'])),
    Node(1643273, frozenset(['1783604', '1783603']), frozenset(['GARDNER'])),
    Node(1801071, frozenset(['1963032', '1963031']), frozenset(['CHAPMAN', 'EVANS'])),
    Node(1836980, frozenset(['2004300', '2004301']), frozenset(['BOYD'])),
    Node(10298940, frozenset(['2004300', '2004301']), frozenset(['BOYD'])),
    Node(1843190, frozenset(['2011505']), frozenset(['CHAPMAN'])),
    Node(1905248, frozenset(['2082776']), frozenset(['GARDNER'])),
    Node(1927031, frozenset(['2108156', '2108157']), frozenset(['FOX'])),
    Node(2039106, frozenset(['2236190', '2236191']), frozenset(['FOX'])),
])


texts: Reinitialize cache periodically, catching and logging any Throwables

texts:
My existing code has a scheduler that we init when a DataStore constructor is called.

private void initSchedulers() {
    int initialDelay = applicationStartupConfig.getSchedulerInitialDelay();
    int refreshPeriod = applicationStartupConfig.getSchedulerRefreshPeriod();
    // above are fetched using config.yml(dropwizard)

    Timer timer = new Timer(true);
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            try {
                initializeCache(); // some operation that we perform to fetch data on to the cache on a scheduled basis
            } catch (Throwable t) {
                logger.error("Scheduler could not complete : ", t);
            }

        }
    }, initialDelay, refreshPeriod);
}

Evaluating the code under Sonar Analysis reports this as Vulnerable --

  Throwable is the superclass of all errors and exceptions in Java.

  Error is the superclass of all errors, which are not meant to be
  caught by applications.

  Catching either Throwable or Error will also catch OutOfMemoryError
  and InternalError, from which an application should not attempt to
  recover.

Though I understand the above statements yet I am not able to draw a conclusion on

What if I catch Exception today, and a runtime error exception is thrown later? Would that not stop the scheduler?
Is there a way to specify handling both these cases and ensuring that this does not create impact on client calls to the DataStore?


texts: Quicksort implementation using filter() to perform partitioning

texts:
from operator import ge as greater, lt as lesser

def qsort(L):
    if len(L) <= 1: return L
    pivot   = L[0]
    sublist = lambda op: [*filter(lambda num: op(num, pivot), L[1:])]

    return qsort(sublist(lesser))+ [pivot] + qsort(sublist(greater))

It seems like an overkill to have two lambdas in the sublist definition. How can I refactor the sublist lambda function to not include lambda at all?


texts: Validate IP address and create a registration attempt

texts:
I'm a C++/Python developer attempting to learn JavaScript, but I'm struggling to write clean code.  I've read that async.waterfall and Promises are two ways to flatten the code a bit, but my implementation seems far more inflated than what I've grown accustomed to using Python.  Is there anything that I can do to refactor the below code sample to compact it without failing to handle errors?

nodejs Implementation:

Authenticator.prototype.register = function(opts) {
  var self = this;
  return new Promise(function(resolve, reject) {
    self.__validateIpAddress(opts.ip)
    .then(function() {
      self.__createRegisterAttempt(opts)
      .then(function(attempt) {
         // ...
      }, function(err) {
        reject(err);
      }
    }, function(err) {
      reject(err);
    });
  });
};

Python Implementation: (for comparison)

class Authenticator(object):
    # caller must handle exceptions
    def register(self, opts):
        self.__validateIpAddress(opts['ip'])
        attempt = self.__createRegisterAttempt(opts)
        # ...


texts:
I have here some methods which reverse string characters. Example if given string is "HELLO", it will returns "OLLEH". Are my big o notation for these approaches correct? And which approach is the most efficient (both time and space complexity)?

 /// <summary>
    /// Time Complexity: o(n)
    /// Space Complexity: o(n)
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string ReverseString_TwoArrays(string str)
    {
        char[] arr2 = new char[str.Length];

        for (int i = 0; i < str.Length; i++)
        {
            arr2[i] = str[str.Length - 1 - i];
        }
        return string.Join("",arr2);
    }

    /// <summary>
    /// Time Complexity: o(n)
    /// Space Complexity: o(1)
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string ReverseString_ClassicForLoop_ArrayIndex(string str)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = str.Length - 1; i >= 0; i--)
        {
            sb.Append(str[i]);
        }
        return sb.ToString();
    }

    /// <summary>
    /// Time Complexity: o(n)
    /// Space Complexity: o(1)
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string ReverseString_ForEachConcat(string str)
    {

        string newStr = "";
        foreach (var item in str)
        {
            newStr = item.ToString() + newStr;
        }
        return newStr;
    }

    /// <summary>
    /// Time Complexity: o(n)
    /// Space Complexity: o(n)
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string ReverseString_Stack(string str)
    {
        var stack = new Stack();
        foreach (var item in str) // Time Complexity: o(n)
        {
            stack.Push(item); // Time Complexity: o(1)
        }
        return string.Join("", stack.ToArray());
    }

    /// <summary>
    /// Time Complexity: o(n)
    /// Space Complexity: o(n)
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string ReverseString_ArrayReverse(string str)
    {
        char[] arrChar = str.ToCharArray();
        Array.Reverse(arrChar);
        return string.Join("", arrChar);
    }

    /// <summary>
    /// Time Complexity: o(n)
    /// Space Complexity: o(1)
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string ReverseString_LINQ(string str)
        => string.Join("", str.Reverse());


texts:
Below is my bash script to setup a proxy, I am by no means an expert in bash. I suspect there is a better way to write this, any tips would be appreciated.

Is there a better way to do nested while-loops and if-statements?

#!/bin/bash
set -e

#functions
function yesno() {
  while read -n1 -r -p "[y/n/QUIT] > "; do
    case $REPLY in
      y|n) return;;
      q) echo; echo; exit 1;;
      *) printf "\nERROR - Invalid response, please enter Yes OR No.\n";;
    esac
  done
}

function startover() {
  printf "\n\n\e[1m\e[31mStarting Over...\e[0m\n"
  sleep 2
  unset proxyport proxyhost
}

    shopt -s nocasematch
    while true; do
      printf "\nIs a proxy required to access outbound \e[1m\e[7mHTTP/HTTPS\e[0m sites?\n"
      yesno
      if [[ $REPLY == "y" ]]; then
        printf "\n\nPlease enter your proxy url\nExample - \e[1m\e[7mproxy.example.com:8080\e[0m\n"
        while read -r -p "Proxy > " proxy; do
          if [[ $proxy =~ ^https:// && $proxy =~ :[0-9]{1,5}$ ]]; then
            printf "\nERROR - HTTPS with a port is not supported, please re-enter without '\e[1m\e[97m\e[41mHTTPS://\e[0m' prefix\n"
          elif [[ $proxy =~ ^(https?://)?([a-z0-9][-a-z0-9\.]{0,61}[a-z0-9]\.[a-z]{2,5})?.((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))?(:[0-9]{1,5})?$ ]]; then
            if [[ $proxy =~ :[0-9]{1,5}$ ]]; then
              proxyport=${proxy##*:}
              proxy=${proxy%:*}
              echo "Port entered $proxyport"
            elif [[ $proxy =~ ^https:// && ! $proxy =~ :[0-9]{1,5}$ ]]; then
              proxyport=443
              echo "URL starts with HTTPS, assuming $proxyport"
            else
              proxyport=80
              echo "No port entered, assuming $proxyport"
            fi
            proxyhost=${proxy##*/}
            break
          else
            printf "\nERROR - \e[1m\e[97m\e[41m$proxy\e[0m is not supported please try again\n"
          fi
        done
        printf "\nCreating Proxy Settings\n"
        sleep 2
        printf "Proxy Hostname: \e[1m\e[97m\e[44m$proxyhost\e[0m\nProxy Port: \e[1m\e[97m\e[44m$proxyport\e[0m\nDoes the information above look correct?\n"
        yesno
        if [[ $REPLY == "n" ]]; then
          startover
        fi
      fi
      break
    done
    shopt -u nocasematch

Update 4/6/17
I have improved the regex so it now supports IP and hostnames, i am still working on actually setting the proxy settings.


texts: Java generics with wildcard vs non generic List to deal with non generic data

texts:
There is a problem on Exercism Java track that requires writing a function to flatten an arbitrarily nested list to a flattened list without null values.
For Example
input: [1,[2,3,null,4],[null],5]
output: [1,2,3,4,5]
Here is the solution I wrote for it without using wildcards.
public List flatten(List<Object> two) {
    Function<Object, List> mapper = item -> (item instanceof List) ? flatten((List) item) : Collections.singletonList(item);
    return (List) two.stream()
            .filter(x -> x != null)
            .map(mapper)
            .flatMap(x -> x.stream())
            .collect(Collectors.toList());
}

Here is my solution with the wildcard generics. My IDE was happier with this solution.
public List<Object> flatten(List<?> two) {
    Function<Object, List<?>> mapper = item -> (item instanceof List) ? flatten((List<?>) item) : Collections.singletonList(item);
    return two.stream()
            .filter(Objects::nonNull)
            .map(mapper)
            .flatMap(List::stream)
            .collect(Collectors.toList());
}

Is it ok to use the wildcard in this case? Which solution would you prefer? Any other comments about the code are also welcome.


texts: Parse date format in Pandas using Python

texts:
I have a column in a Pandas Dataframe containing birth dates in object/string format:

0    16MAR39
1    21JAN56
2    18NOV51
3    05MAR64
4    05JUN48

I want to convert the to date formatting for processing. I have used

#Convert String to Datetime type
data['BIRTH'] = pd.to_datetime(data['BIRTH'])

but the result is ...

0   2039-03-16
1   2056-01-21
2   2051-11-18
3   2064-03-05
4   2048-06-05
Name: BIRTH, dtype: datetime64[ns]

Clearly the dates have the wrong century prefix ("20" instead of "19")

I handled this using ...

data['BIRTH'] = np.where(data['BIRTH'].dt.year > 2000, data['BIRTH'] - pd.offsets.DateOffset(years=100), data['BIRTH'])

Result

0       1939-03-16
1       1956-01-21
2       1951-11-18
3       1964-03-05
4       1948-06-05

Name: BIRTH, Length: 10302, dtype: datetime64[ns]

I am wondering:

if there is a way to process the data that will get it right first time?
If there is a better way to process the data after the incorrect conversion.

I'm an amateur coder and as far as I understand things Pandas is optimised for processing efficiency. So I wanted to use the Pandas datatime module for that reason. But is it better to consider Numpy's or Pandas' datetime module here? I know this dataset is small but I am trying to improve my skills so that when I am working on larger datasets I know what  to consider.

Source data


texts: Print a pattern of text based on a line from an Excel file

texts:
I started to learn Python not long ago to automate certain tasks I work on. I want to optimize a script I wrote that takes a line in an Excel file and prints a pattern of text based on this line's content. Here's an example of output from my code:

mgmt_cli add access-rule layer "network" position bottom name "thirdline" source.1 "Value1front" source.2 "Value2front" source.3 "x3front" destination "Dest1front" service "HTTP" track.type "Log" action "Accept"

How would you optimize this code?

Link to the example file (just click Valider et Télécharger le Fichier) http://dl.free.fr/hFlGmywIN
Link to full code : https://pastebin.com/CR5SXHRQ

import xlrd
import re
loc = ("Dir\StackoverflowExample.xlsx")

wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)

# Extracting number of rows

def CaseMulti(CellContent, CellName):
 #takes a cell and a string as parameters, prints a pattern like Cell.X ="string", X starts with 0 and ends at the number of line in the Cell
 case = str(CellContent)
 x= re.split ("\s", case)   #splits the cell contents in a list using regex where space is the separator for the list's elements
 if name == CellContent:  # deals with the cell with spaces between objects no clue how it work but it does
  return "name " + '"{}"'.format(CellContent)
 else:
  s=0
  string =""
  anycells = ["any","Any", "ANY"]  # tests if the soure, destination or service has any ==> returns nothing
  if str(x[0]) in anycells :
   return " "
  else:
   if len(x)==1:    # case where te cell has one line (or a word with no spaces)
    string= CellName + " " +'"{}"'.format(case)

   else:            # case where multilines/mutli spaces
    while s<len (x) :
     listelement = x[s]
     string = string + CellName+'.'+str(s+1)+ ' '  +'"{}"'.format(listelement)
     s=s+1

   return string

for numberofrows in range (5):

 print "Rule " + str (numberofrows)
 name= sheet.cell_value(numberofrows,1)
 source = sheet.cell_value(numberofrows,2)
 destination = sheet.cell_value(numberofrows,3)
 protocole = sheet.cell_value(numberofrows,4)
 log = sheet.cell_value(numberofrows,5)
 action = sheet.cell_value(numberofrows,6)
 #firewall = sheet.cell_value(numberofrows,7)

 try:
  print ("mgmt_cli add access-rule layer \"network\" position bottom " + str(CaseMulti(name,"name")) +  str(CaseMulti(source, " source")) + str(CaseMulti(destination, " destination")) +  str(CaseMulti(protocole, " service")) +   ' track.type "Log" ' + str(CaseMulti(action, " action")) )
 except :
  numberofrows +=1


texts:
I am working on sending a reset token via email to a potential user in Node.js, Sequelize, and Express.

The code works, but I still think it could be improved by handling the promises better.

exports.sendResetToken = function(req,res) {
  const username = req.headers.username;
  User.findOne({
    where: {username: username}
  }).then((user) => {
    if(user == null){
      res.sendStatus(404);
    } else {
      let token = user.generateResetToken();
      user.update({
        resetToken: token,
      }).then((user) => {
        email.sendResetToken(user.email,user.resetToken);
        res.sendStatus(200);
      }).catch((err) => {
        console.error(err);
        res.sendStatus(400);
      })
    }
    return null;
  }).catch((err) => {
    console.error(err);
    res.sendStatus(401);
  })
}


texts:
This is a solver for Sudoku using backtracking.  How can I make it more optimized and clean?

#include <stdio.h>

int isAvailable(int sudoku[][9], int row, int col, int num)
{
    int i, j;
    for(i=0; i<9; ++i)
        if( (sudoku[row][i] == num) || ( sudoku[i][col] == num )  )//checking in row and col
            return 0;

     //checking in the grid
    int rowStart = (row/3) * 3;
    int colStart = (col/3) * 3;

    for(i=rowStart; i<(rowStart+3); ++i)
    {
        for(j=colStart; j<(colStart+3); ++j)
        {
            if( sudoku[i][j] == num )
                return 0;
        }
    }

    return 1;
}

int fillsudoku(int sudoku[][9], int row, int col)
{
    int i;
    if( row<9 && col<9 )
    {
        if( sudoku[row][col] != 0 )//pre filled
        {
            if( (col+1)<9 )
                return fillsudoku(sudoku, row, col+1);
            else if( (row+1)<9 )
                return fillsudoku(sudoku, row+1, 0);
            else
                return 1;
        }
        else
        {
            for(i=0; i<9; ++i)
            {
                if( isAvailable(sudoku, row, col, i+1) )
                {
                    sudoku[row][col] = i+1;

                    if( (col+1)<9 )
                    {
                       if( fillsudoku(sudoku, row, col +1) )
                           return 1;
                        else
                            sudoku[row][col] = 0;
                    }
                    else if( (row+1)<9 )
                    {
                        if( fillsudoku(sudoku, row+1, 0) )
                            return 1;
                        else
                            sudoku[row][col] = 0;
                    }
                    else
                        return 1;
                }
            }
        }
        return 0;
    }
    else
    {
        return 1;
    }
}

int main()
{
   int i, j;
    int sudoku[9][9]={{3, 0, 6, 5, 0, 8, 4, 0, 0},
                      {5, 2, 0, 0, 0, 0, 0, 0, 0},
                      {0, 8, 7, 0, 0, 0, 0, 3, 1},
                      {0, 0, 3, 0, 1, 0, 0, 8, 0},
                      {9, 0, 0, 8, 6, 3, 0, 0, 5},
                      {0, 5, 0, 0, 9, 0, 6, 0, 0},
                      {1, 3, 0, 0, 0, 0, 2, 5, 0},
                      {0, 0, 0, 0, 0, 0, 0, 7, 4},
                      {0, 0, 5, 2, 0, 6, 3, 0, 0}};

    if( fillsudoku(sudoku, 0, 0) )
    {

        for(i=0; i<9; ++i)
        {
            for(j=0; j<9; ++j)
                printf("%d ", sudoku[i][j]);
            printf("\n");
        }
    }
    else
    {
        printf("\n\nNO SOLUTION\n\n");
    }

    return 0;
}


texts:
I have written a small tool to generate a json file from sqlalchemy models files to automate the tedious procedure of writing all the sql raws in a json format. The script works, but there are few parts, see get_modules function, that can be improved. I would be glad to have a review of this code. Thanks

# -*- coding: utf-8 -*-

import os
import sys
import glob

PATH = sys.argv[1]
output_filename = 'en.json'

intro = ("""
{
  "sidebar": {
      "overview": "Overview",
  },
  "about": {
      "title": "title"
    },
    "welcome": {
        "title": "Welcome to the prototype app!"
    },

""")

def get_fields(input_filename):
    """It returns all fields of a model in a list"""
    fields = []
    endpoint = None
    with open(PATH+input_filename, 'r') as inputfile:
        for line in inputfile:
            if '__plural_name__' in line:
                endpoint = line.split('=')[1].strip().replace("'","")
            if '= Column' in line:
                fields.append(line.split()[0])
    return endpoint, fields

def get_modules():
    """It returns a list of all models"""
    files = []
    cwd = os.getcwd()
    os.chdir(PATH)
    files = glob.glob("*.py")
    os.chdir(cwd)
    return files

if __name__ == "__main__":

    models = get_modules()
    target = open(output_filename, 'w')
    target.write(intro)
    for m in models:
        if m != '__init__.py':
            end_name, attrs = get_fields(m)
            target.write('  "{}": {{\n'.format(end_name))
            target.write('    "title": "{}",\n'.format(end_name))
            target.write('    "fields": {\n')
            for a in attrs:
                target.write('      "{}": "{}",\n'.format(a,a))
            target.write('    }\n')
            target.write('  },\n')
    target.close()


texts: Searching for files across multiple code projects

texts:
I was tasked with conducting a large number of text searches in the code files of multiple projects. Initially, I just used the Find in Files feature of Visual Studio in a couple of the running instances, but then I realized I needed to search other solutions as well.  So I quickly created an F# Script (below) to conduct the searches across all code files async.

For all matching results, the script prints:

C:\path-to-file
linenumber: line of code

How can this be improved?  The script runs extremely fast and did its job well.  Now, out of curiosity, I would like to know what improvements could be made to optimize performance?

open System
open System.IO

let directory = @"C:\path-to-top-level-directory"

// this just keeps async operations from writing to the console concurrently (garbled result)
let agent = MailboxProcessor.Start(fun inbox ->
    // the message processing function
    let rec messageLoop () = async {
        let! msg = inbox.Receive()
        printfn "%s" msg
        return! messageLoop()
    }
    // start the loop
    messageLoop ()
)

let checkIfContains value file = async {
    use reader = new StreamReader(File.OpenRead(file))
    let lineNum = ref -1
    let postResult (i, s) = sprintf "%s\r\n%i: %s\r\n" file i s |> agent.Post

    seq { while not reader.EndOfStream do
            incr lineNum
            yield (!lineNum, reader.ReadLine()) }
        |> Seq.filter (fun (_, s) -> s.Contains(value))
        |> Seq.iter postResult
}

let files =
    Directory.EnumerateFiles(directory, "*.vb", SearchOption.AllDirectories)
        |> Seq.append (Directory.EnumerateFiles(directory, "*.cs", SearchOption.AllDirectories))

while true do
    agent.Post "Search string: "
    let value = Console.ReadLine()
    agent.Post "Searching...\r\n"

    files
        |> Seq.map (checkIfContains value)
        |> Async.Parallel
        |> Async.RunSynchronously
        |> ignore

    agent.Post "\r\nDone.\r\n\r\n"


texts: Define a class for latitude and longitude in C++ using boost::units and spheroidal coordinates

texts:
I am trying to write a class that defines latitude and longitude in C++ using boost::units and normalized spheroidal coordinates.  I want to throw an exception if the class is constructed outside the bounds of the normalized spheroidal coordinates.  Incidentally I thought about using boost::geometry but when I read this forum discussion it looked like converting between using boost::units and boost::geometry was not straightforward, so I am just making the below and am wondering if this is a good path to go down.

#include <boost/units/quantity.hpp>
#include <boost/units/systems/si/plane_angle.hpp>
#include <boost/units/systems/angle/degrees.hpp>
#include <boost/units/base_units/angle/radian.hpp>
#include <boost/units/base_units/angle/degree.hpp>
#include <boost/math/constants/constants.hpp>

namespace units = boost::units;
namespace si = units::si;
namespace constants = boost::math::constants;

class Latitude
{
private:
  units::quantity<si::plane_angle> angle;

public:
  Latitude(units::quantity<si::plane_angle> angle) : angle(angle)
  {
    assert (angle <= ( constants::half_pi<double>() * si::radians));
    assert (angle >= (-constants::half_pi<double>() * si::radians));
  }

  const units::quantity<si::plane_angle> value()
  {
    return angle;
  }

};

class Longitude
{
private:
  units::quantity<si::plane_angle> angle;

public:
  Longitude(units::quantity<si::plane_angle> angle) : angle(angle)
  {
    assert (angle <= ( constants::pi<double>() * si::radians));
    assert (angle >= (-constants::pi<double>() * si::radians));
  }

  const units::quantity<si::plane_angle> value()
  {
    return angle;
  }

};


texts:
I am looking for help for two things:
1.how precise this approximation is (such as Big O or percent error)
2. How efficient the algorithm for time / space usage.
I created an algorithm to estimate an integral. The algorithm creates squares and adds the estimate of the remain sum times the area together. Since this function is 2d, the area is multiplied by f(x, y) at a point. The function in this program is f(x, y) = x + (a * y).
The documented code is below.

def f(x:float, y:float, a:float)->float:
    """
    param x:float, x within the function domain
    param y:float, y within the function domain
    param a:float, a paramter of the curve
    Output: Number of function at the point
    """
    return x + (a * y)

class Square:
    def __init__(self, xi:float, yi:float, xf:float, yf:float)->None:
        """
        param xi:float, smaller coordinate of x
        param yi:float, smaller coordinate of y
        param xf:float, larger cooordinate of x
        """
        self.xi = xi
        self.yi = yi
        self.xf = xf
        self.yf = yf

    def estimate(self, a:float)->float:
        """
        param a:float, a from the curve paramter
        Output: a term to add to estimate the intergal
        """
        xd = self.xf - self.xi
        yd = self.yf - self.yi
        if xd < 0:
            xd = xd * -1
        if yd < 0:
            yd = yd * -1
        area_delta = xd * yd
        est = f(self.xi, self.yi, a)
        return area_delta * est

def main()->None:
    """"
    Input: None
    Output:None
    Note: driver program
    """
    x = [1.0, 2.0, 3.0]
    y = [2.0, 3.0, 4.0]
    a = 1.0
    add = 0.0
    square = None
    for row in range(len(x)):
        for col in range(len(x)):
            if row <= col:
                continue
            square = Square(x[row], y[row], x[col], y[col])
            add = add + square.estimate(a)
    print(add)

if __name__ == "__main__":
    main()

``


texts: My implementation of bubble sort using Python

texts:
I just started studying algorithms and since I'm most familiar with Python decided to use it to actually put the algorithms I've been learning to use. How is my implementation of Bubble Sort? Does it make sense, is it efficient, too many variables, can you understand it without comments, any other tips for me?

"""
Bubble sort algorithm.
"""
import random
ls = []
max_length = 10
while len(ls) < max_length:
    ls.append(random.randint(1,101))
print ls
def bubble_sort(items_to_sort):
    right_item = -1
    left_item = -2
    item_len = len(items_to_sort)
    number_of_passes = 0
    temp_item = 0
    max_checks = len(items_to_sort)
    if item_len > 1:
        while (number_of_passes < item_len) and (max_checks > 0):
            if items_to_sort[right_item] < items_to_sort[left_item]:
                temp_item = items_to_sort[right_item]
                items_to_sort[right_item] = items_to_sort[left_item]
                items_to_sort[left_item] = temp_item
            right_item += -1
            left_item += -1
            number_of_passes += 1
            if left_item < -(item_len):
                right_item = -1
                left_item = -2
                number_of_passes = 0
                max_checks -= 1
    return items_to_sort
print bubble_sort(ls)


texts:
Recently, I read a article about work stealing queue  Job System 2.0: Lock-Free Work Stealing – Part 3: Going lock-free, and this is my c++11 naive implementation based on my understand of c++11 memory order model. This works on x86 , as x86 has a strong memory model, is there any issue running on other architecture (weak memory order)?

#include <atomic>

class Job;

struct WorkStealingQueue
{
    // only called by owner work thread
    void Push(Job* job) noexcept
    {
        // m_bottom -> stealing thread read, owner thread read, write.
        auto bottom = m_bottom.load(std::memory_order_relaxed);

        m_jobs[bottom & MASK] = job;

        // need  let stealing thread see the new job.
        m_bottom.fetch_add(1, std::memory_order_release);
    }

    // only called by owner worker thread
    Job* Pop(void) noexcept
    {
        auto bottom = m_bottom.load(std::memory_order_relaxed);

        auto top = m_top.load(std::memory_order_acquire);

        if (bottom > top)
        {
            auto job = m_jobs[(bottom - 1) & MASK];

            if(top < (bottom - 1))
            {
                m_bottom.fetch_sub(1, std::memory_order_release);
                return job;
            }
            if (m_top.compare_exchange_weak(
                top, top + 1,
                std::memory_order_release,
                std::memory_order_relaxed))
            {
                return job;
            }
        }

        return nullptr;
    }

    // called by stealing thread, not owner thread
    Job* Steal(void) noexcept
    {
        auto top = m_top.load(std::memory_order_acquire);

        // Release-Acquire ordering, so the stealing thread see new job
        auto bottom = m_bottom.load(std::memory_order_acquire);

        if (bottom > top)
        {
            auto job = m_jobs[top & MASK];
            // check if other stealing thread stealing this work
            // or owner thread pop this job.
            // no data should do sync, so use relaxed oreder
            if (m_top.compare_exchange_weak(
                top, top + 1,
                std::memory_order_release,
                std::memory_order_relaxed))
            {
                return job;
            }
        }

        return nullptr;
    }

private:

    static constexpr auto MAX_COUNT = 4096u;
    static constexpr auto MASK = MAX_COUNT - 1u;
    static_assert((MAX_COUNT & MASK) == 0, "the max number of job must be power of two.");

    Job* m_jobs[MAX_COUNT];
    std::atomic<unsigned int> m_bottom{ 0 }, m_top{ 0 };
};


texts: Which linq statement is better to find there is an overlap between two lists of ints?

texts:
I'm wondering about the difference between these two linq statements

bool overlap = GetMyListA().Intersect(GetMyListB()).Any(); // 1.

vs

bool overlap = GetMyListA().Any(i => GetMyListB().Contains(i)); // 2.

Will statement 2. call GetMyListB() for each item in ListA?

Which is more readable?


texts: VBA - recursive combination listing based on Excel columns

texts:
I have rewritten a recursive procedure to list combinations of values in Excel columns in a way, that instead of one cell string output, there is an array output to Excel range (one value per cell, one combination per row). It lists up to 1 000 000 combinations and executes in 45 seconds / 1 000 000 combinations on my PC. Are any improvements which would let me decrease execution time possible?

   Sub ListCombinations()

    Dim arr As Variant, outCnt As Long, vOut() As Variant
    Dim lastRow As Long
    Dim tim As Double: tim = Timer

    arr = ThisWorkbook.Worksheets("assignment optimization").Range("b2:j12")
    ReDim vOut(1000000, UBound(arr, 2))
    outCnt = 1
    Arrangements arr, vbNullString, LBound(arr, 2), outCnt, vOut

    Application.ScreenUpdating = False

    With ThisWorkbook.Worksheets("assignment optimization")
        With Range(.Cells(1, 12), .Cells(outCnt, 11 + UBound(vOut, 2)))
            lastRow = .Columns.Find(what:="*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
            .Columns.ClearContents
            .Value = vOut
        End With
    End With

    Application.ScreenUpdating = True

    Debug.Print Timer - tim

End Sub

Sub Arrangements(ByRef arr, ByVal s As String, ByVal lInd As Long, ByRef outCnt As Long, ByRef vOut As Variant)

Dim i As Long, arrayIndex1 As Long

    For i = LBound(arr) To UBound(arr)
        If arr(i, lInd) <> False Then 'exclude values "FALSE" from listing
            If lInd = UBound(arr, 2) Then
                For arrayIndex1 = LBound(vOut, 2) To UBound(vOut, 2)
                    vOut(outCnt, arrayIndex1) = Split(Mid$(s, 2) & "," & arr(i, lInd), ",")(arrayIndex1 - 1)
                Next arrayIndex1
                If outCnt = 1000000 Then Exit Sub
                outCnt = outCnt + 1
            Else
                vOut(outCnt, lInd) = arr(i, lInd)
                Arrangements arr, s & "," & arr(i, lInd), lInd + 1, outCnt, vOut
            End If
        End If
    Next i

End Sub

Edit:

I already found first improvement. Instead of splitting the same string on each arrayIndex1 iteration, I do the splitting outside of the loop and assign it to array. Execution time is now 18 seconds.

Dim outVals () as string

...

outVals = Split(Mid$(s, 2) & "," & arr(i, lInd), ",")

For arrayIndex1 = LBound(vOut, 2) To UBound(vOut, 2)
    vOut(outCnt, arrayIndex1) = outVals(arrayIndex1 - 1)
Next arrayIndex1

Edit 2:

Combinations input and output layout:


texts:
I have the List method that takes sorting parameter to sort results.  The sorting parameter value is the same as the column name.

public ActionResult List(string sorting = "Name", string sortingMethod = "ASC")
{
    var productList = productRepository.Get();

    if(!String.IsNullOrEmpty(Sorting){
        if(String.IsNullOrEmpty(SortingMethod) ||SortingMethod == "ASC"){
            switch(sorting){
                case "Name" :
                    productList = productList.OrderBy(x => x.Name); break;
                case "Price" :
                    productList = productList.OrderBy(x => x.Price); break;
                case "Category" :
                    productList = productList.OrderBy(x => x.Price); break;
                //...
            }
        }else{
            switch(sorting){
                case "Name" :
                    productList = productList.OrderByDescending(x => x.Name); break;
                case "Price" :
                    productList = productList.OrderByDescending(x => x.Price); break;
                case "Category" :
                    productList = productList.OrderByDescending(x => x.Price); break;
                //...
            }
        }
    }

    return View(productList.ToList());
}

But I believe there is a better way to make code shorter.

public ActionResult List(string sorting = "Name", string sortingMethod = "ASC")
{
    var productList = productRepository.Get();

    if(!String.IsNullOrEmpty(Sorting){
        if(String.IsNullOrEmpty(SortingMethod) ||SortingMethod == "ASC"){
            productList = productList.OrderBy();  // <== ???
        }else{
            productList = productList.OrderByDescending(); // <== ???
        }
    }

    return View(productList.ToList());
}


texts: Find non duplicateTriangle Triplets from a list of given numbers

texts:
I implemented an O(N^2) algorithmic  solution but not sure it is better than my previous implementation Find Triangle Triplets from a list of given numbers
 in case of performance. I adapted almost all suggestions from answer except a structure to keep the triangle triplets.The reasons to ignore the suggestion are follows:

This program added additional feature to remove duplicates from the output
To achieve this additional feature in better way is to keep the data structure as vector instead of  suggested data structure 'structure' in place of vector.
Moreover there is no additional advantage, instead a change in the coding  style  with this suggested change in my perspective

And @nhgrif pointed out in chat my previous solution spitting duplicate triplets and that flaw is taken care here. Let me know is there any other option to make my code better.

#include<vector>
#include<iostream>
#include<algorithm>
#include<set>

bool isTriangleTriplet(const int a, const int b, const int c)
{
    if( ( a + b ) > c &&  ( a + c ) > b && ( b + c ) > a)
    {
        return true;
    }
    return false;
}
std::vector<std::vector<int>> findTriangleTriplets( const std::vector<int>& vec_input )
{
    auto size =  vec_input.size();
    std::vector<std::vector<int>>  triplets;
    for( unsigned int i = 0; i < size; ++i )
    {
        for( unsigned int j = i+1; j < size; ++j )
        {
            std::vector<int> temp;
            temp.emplace_back( vec_input.at( i ) );
            temp.emplace_back( vec_input.at( j ) );
            triplets.emplace_back( temp );
    }   }
    std::vector<std::vector<int>>  temp_triplets;

    for(auto &pair : triplets)
    {
        std::vector<int> pers_vec( pair );
        bool flag = false;
        for( auto &num : vec_input )
        {
            if( isTriangleTriplet( pair.at( 0 ), pair.at( 1 ) , num) )
            {
                if( flag )
                {
                    std::vector<int> temp( pers_vec );
                    temp.emplace_back( num );
                    temp_triplets.push_back( temp );
                }
                else if( std::count( std::begin( pair ), std::end( pair ), num ) < 2 )
                {
                    pair.emplace_back( num );
                    flag=true;
                }
            }
        }
    }

    for( auto & x: temp_triplets )
    {
        triplets.emplace_back( x );
    }
    return triplets;
}

std::set<std::vector<int>> SieveDuplicates( std::vector<std::vector<int>> & triplets )
{
    std::set<std::vector<int>> sieved_triplets;
    for( auto &x : triplets )
    {
        std::sort( std::begin( x ), std::end( x ) );
        sieved_triplets.emplace( x );
    }
    return sieved_triplets;
}

int main()
{
    const std::vector<int> vec_input { 2, 3, 4, 1, 5, 6};
    std::vector<std::vector<int>>  triplets = findTriangleTriplets( vec_input );
    std::cout<< "Triplet size:" << triplets.size()<<"\n";
    for ( auto &x : triplets)
    {
        for( auto &y : x )
        {
           std::cout<<y<<" ";
        }
        std::cout<<"\n";
    }

    std::set<std::vector<int>> sieved_triplets=SieveDuplicates( triplets );
    std::cout<< "Sieved Triplet size:" << sieved_triplets.size()<<"\n";
    for ( auto &x : sieved_triplets )
    {
        for( auto &y : x )
        {
           std::cout<<y<<" ";
        }
        std::cout<<"\n";
    }
}


texts:
I am writing a numerical analysis library in golang for which I need to implement a polynomial struct. Here is the source code:

package numerical

import (
    "strconv"
)

type Poly struct {
    Coeffs []float64
}

func (p *Poly) Str() string {
    d := p.Deg()

    if d == -1 {
        return "0"
    }

    s := ""
    if p.Coeffs[d] == -1 {
        if d == 0 {
            s += "-1"
        } else {
            s += "-"
        }
    } else if p.Coeffs[d] != 1 || d == 0 {
        s += strconv.FormatFloat(p.Coeffs[d], 'g', -1, 64)
    }
    if d == 1 {
        s += "x"
    } else if d > 1 {
        s += "x^" + strconv.Itoa(d)
    }
    for i := d-1; i >= 0; i-- {
        if p.Coeffs[i] > 0 {
            s +=  " + "
            if p.Coeffs[i] != 1 || i == 0 {
                s += strconv.FormatFloat(p.Coeffs[i], 'g', -1, 64)
            }
        } else if p.Coeffs[i] < 0 {
            s += " - "
            if p.Coeffs[i] != -1 || i == 0 {
                s += strconv.FormatFloat(-p.Coeffs[i], 'g', -1, 64)
            }
        }
        if p.Coeffs[i] != 0 {
            if i == 1 {
                s += "x"
            } else if i > 1 {
                s += "x^" + strconv.Itoa(i)
            }
        }
    }

    return s
}

func (p *Poly) Deg() int {
    i := len(p.Coeffs) - 1
    for ; i >= 0 && p.Coeffs[i] == 0; i-=1 {
    }
    return i
}

func (p *Poly) Eval(x float64) float64 {
    val := p.Coeffs[0]
    pow := 1.0
    for i:=1; i <= p.Deg(); i+=1 {
        pow *= x
        val += p.Coeffs[i]*pow
    }
    return val
}

func PolyAdd(p, q Poly) Poly {
    var big, small, r Poly
    if p.Deg() > q.Deg() {
        big = p
        small = q
    } else {
        big = q
        small = p
    }
    r = big
    for i := 0; i <= small.Deg(); i+=1 {
        r.Coeffs[i] += small.Coeffs[i]
    }
    return r
}

func PolySub(p, q Poly) Poly {
    degp := p.Deg()
    degq := q.Deg()
    big := degp
    if degp < degq {
        big = degq
    }
    r := Poly{make([]float64, big+1)}
    for i := 0; i <= big; i++ {
        if i <= degp {
            r.Coeffs[i] = p.Coeffs[i]
        }
        if i <= degq {
            r.Coeffs[i] -= q.Coeffs[i]
        }
    }
    return r
}

func PolyMul(p, q Poly) Poly {
    m, n := p.Deg(), q.Deg()
    r := Poly{make([]float64, m+n+1)}
    for i := 0; i <= m; i++ {
        for j := 0; j <= n; j++ {
            r.Coeffs[i+j] += p.Coeffs[i]*q.Coeffs[j]
        }
    }
    return r
}

func PolyDiv(a, b Poly) (Poly, Poly) {
    var q Poly
    for b.Deg() <= a.Deg() {
        dega := a.Deg()
        degb := b.Deg()
        qc := a.Coeffs[dega]/b.Coeffs[degb]
        qp := dega - degb
        qi := Poly{make([]float64, qp+1)}
        qi.Coeffs[qp] = qc
        a = PolySub(a, PolyMul(qi, b))
        q = PolyAdd(q, qi)
    }
    return q, a
}

A few things that I observed about the code are:

The Poly.Deg is a method. I should probably make a non-method field (what are they called?) for that purpose, but then I will have to create a Poly.UpdateDeg which will set the degree for a new polynomial, and then I will have to call this UpdateDeg in all the other functions like PolyAdd, PolyMul etc. Is their a better way to achieve this.
The Poly.Str method, which basically pretty-prints the polynomial looks very complicated. The purpose of this method is to return a string containing the polynomial in human readable form. For example, the polynomial {-1, 2, -1} will give -x^2 + 2x - 1 (pay special attention to the leading coefficients and spaces around + and -). Can this method be simplified?

Any other suggestion/improvements are welcome, in particular, I would like to know if the code is idiomatic Go. I am new to Go, and would like to learn the Go-way of doing things.

EDIT: Here is the code on Playground (slightly modified to run on Playground).


texts:
I am writing this code in the controller. I want to know is this the right way to write it or not. Because I don't want to write If else conditions and then either redirect or render the pages.

Here is my sample code :

def create
    @stud = Student.new params[:student]
    @stud.save!
    redirect_to students_path(@stud)
  rescue
    render 'new'
end


texts:
My code does what it's suppose to do but the code is failing Pylint checks.
After pasting my code into Pylint checker, it says that Too many branches (15/12) and its failed me on the Pylint checks.

How can this be cleaned up?

"""Docstring"""
import words

def nicer_englishify_word(word):
    """Docstring"""
    wordx = word.lower()
    wordy = ""
    if wordx.endswith('moo'):
        vowel = True
    else:
        vowel = False
    if vowel == True:
        wordy1 = wordx[-3] + wordx[:-3]
        wordy2 = wordx[:-3]
        if wordy1 in words.get_word_list():
            wordy11 = True
        else:
            wordy11 = False
        if wordy2 in words.get_word_list():
            wordy22 = True
        else:
            wordy22 = False
        if wordy11 == wordy22:
            if wordy11 == True:
                wordy = "sametrue"
            else:
                wordy = "samefalse"
        else:
            if wordy22 == False:
                wordy = "[" + wordx[-3] + wordx[:-3] + "]"
            else:
                wordy = "[" + wordx[:-3] + "]"
        if wordy == "sametrue":
            wordy = wordx[-3] + wordx[:-3] + " or " + wordx[:-3]
            wordy = "<" + wordy + ">"
        if wordy == "samefalse":
            wordy = wordx[-3] + wordx[:-3] + " or " + wordx[:-3]
            wordy = "(" + wordy + ")"
    else:
        wordy = wordx[-3] + wordx[:-3]
    return wordy

def nicer_englishify_sentence(sentence):
    """docstring"""
    stringlist = sentence.split()
    result = ""
    for item in stringlist:
        result = result + nicer_englishify_word(item) + " "
    result = result[:-1]
    return result


texts:
I wrote a simple daily horoscope in Python using Beautiful Soup as scraper. It works fine but the code can use some sort of a... direction if you want to put it that way. I have used underscores in my variable names which is a folly. Please point out how can I correct this and also, please tell me how I can expand this. Thanks you.

import requests
from bs4 import BeautifulSoup

def horoscope(url):
    url_ = url
    page = requests.get(url_)

    soup = BeautifulSoup(page.text, "html.parser")

    horoscope_ = soup.findAll("div", {"class": "block-horoscope-text f16 l20"}, text=True)[0].text

    return horoscope_

if __name__ == '__main__':
    rinput = input("Enter your sign: ")
    sign = str.lower(rinput)
    sign = str.strip(sign)
    url = ''

    signs = ['aries', 'taurus', 'gemini', 'cancer', 'leo', 'virgo', 'libra', 'scorpio', 'sagitarius', 'capricorn',
             'aquarius', 'pisces']

    for index, sign_ in enumerate(signs):
        if sign == sign_:
            url = "https://www.horoscope.com/us/horoscopes/general/horoscope-general-daily-today.aspx?sign={0}".format(
                index + 1
            )

print (horoscope(url))


texts:
I have a method liked_by and it doesn't seem like appropriate as per Ruby style. I need to do it as less as possible.

  def liked_by
    if !object.likes.nil?
      like = Like.where(bonus_id: bonus.id)
      users = []
      like.each do |likes|
        liked_user = User.find_by(id: likes.user_id)
        users.push(liked_user.email)
      end
    end
    return users
  end

The main logic is:

I check if any likes to post available (likes.nil?)
I create users array (users = [])
For each like, I find a user with like.user_id and push this user to the users array

In the end, I return users.


texts: Are there any issues in this `Lazy` implementation?

texts:
I have written following small utility to abstract away the lazy initialization logic. (I tend to use lazy variables quite often.)

Are there any issues in this implementation?

// File: F0.java
public abstract class F0<A> {
  public abstract A apply();
}

// File: Lazy.java
public class Lazy<A> {
  private boolean isInitialized = false;
  private A content;
  private final F0<A> init;

  private Lazy(F0<A> init) {
    this.init = init;
  }

  public static <A> Lazy<A> initializedAs(F0<A> init) {
    return new Lazy<A>(init);
  }

  @Override
  public String toString() {
    return this.get().toString();
  }

  public A get() {
    if (!isInitialized) {
      content = init.apply();
      isInitialized = true;
    }
    return content;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    Lazy lazy = (Lazy) o;
    Object c = this.get();
    if (c != null ? !c.equals(lazy.get()) : lazy.get() != null) {
      return false;
    }
    return true;
  }

  @Override
  public int hashCode() {
    return this.get().hashCode();
  }
}

Edit:

Here is an example usage from the current project I am working on.

final Prerequisite prerequisite = new Prerequisite() {

  private Lazy<String> minimumRequiredJavaVersion = Lazy.initializedAs(
    new F0<String>() {
      @Override
      public String apply() {
        return SystemProperties.isWindows() && SystemProperties.is64Bit() ? "1.7" : "1.6";
      }
    }
  );

  @Override
  public boolean isSatisfied() {
    return SystemProperties.javaVersionIsMinimum(minimumRequiredJavaVersion.get());
  }

  @Override
  public String failureMessage() {
    StringBuilder sb = new StringBuilder();
    sb.append("Minimum required Java version is: " + minimumRequiredJavaVersion.get() + "\n");
    sb.append("Your system has " + JAVA_SPECIFICATION_VERSION + ".");
    return sb.toString();
  }
};


texts: Dependency injecting or manually instantiating structs in others with go

texts:
I am coming from PHP OOP background so just want to find out if what I do with Go is common/acceptable practise or not (I am newbie in Go). It is to do with Dependency Injection.

In OOP it is ideal to Dependency Inject object X into object Y rather than directly instantiating object X in object Y. I won't list the reasons because I believe most of you know general OOP practises etc. Given that Go is not an OOP language and I've seen both versions being used, which version below wins over another an why?

api/internal/config/config.go

package config

type Config struct
{
   Locale string
}

func NewConfig() Config {
   return Config{"en"}
}

VER 1

api/internal/app/app.go

package app

func Start(c config.Config) {
   fmt.Println(c.Locale)
}

cmd/main.go

package main

import (
    "api/internal/app"
    "api/internal/config"
)

func main() {
    c := config.NewConfig()

    app.Start(c)
}

VER 2

api/internal/app/app.go

package app

import (
   "fmt"
   "api/internal/config"
)

func Start() {
   c := config.NewConfig()

   fmt.Println(c.Locale)
}

cmd/main.go

package main

import "api/internal/app"

func main() {
    app.Start()
}


texts: Multiple string replacement (with similarity) using a dictionary

texts:
I'm trying to replace a number of keywords with other corresponding values. I started with this method:

Dictionary<string, string> keywords = GetKeywords();
foreach (var pair in keywords)
{
    var re = new Regex($@"\b{pair.Key}\b");
    if (re.IsMatch(text))
        text = re.Replace(text, pair.Value);
}

..which becomes slower and slower when the number of keywords increases. So, I used a different method (by only scanning the string once and checking each word against the dictionary):

text =
    Regex.Replace(text, @"\w+", delegate (Match m)
    {
        string word = m.Value;
        string value;
        if (keywords.TryGetValue(word, out value))
            return value;
        else
            return word;
    });

..which worked great for the original requirement. However, I was forced to switch back to the first method because I need to match/replace keywords that are not 100% equal to what's in the dictionary. For example, in the first method, I would do something like this:

string keyword = pair.Key.Replace("e", "[eé]")
var re = new Regex($@"\b{keyword}\b");

Is there a way around this using the second method? Or any other methods faster than the first one?

Notes:

It's not just accented letters, so something like IgnoreNonSpace will not work.
Both regex patterns are a little bit more complicated, that is, they both have a negative lookahead ((?![^<]*>|[^&]*;)) but I don't think that affects the outcome as the pattern is essentially just matching single words.

The only solution I could think of is to "normalize" the keywords before adding them to the dictionary (e.g., replace "[eé]" with "e") and then "normalize" each word before passing it to TryGetValue() but I'd like to see if there's a better solution first because this one will be a little bit messy.


texts: JavaScript function to create 2 soccer teams as even as possible, from a list of players

texts:
? Given a list of players with their respective scores (how well does a player play soccer, from 1 to 5 points), return two teams that are as even as possible.

I've created this code, which is a first version, but I really would like to hear about ideas of how can I improve it.

exports.TeamCreator = (function () {

    this.players = [];

    function setPlayers(players){
        this.players = Object.assign([], players);
    }

    function createTeams() {

        var input = this.players;

        var teams = [],
            i = 0,
            scores = [],
            max = input.length;

        scores["A"]=0; scores["B"]=0;
        teams["A"]=[]; teams["B"]=[];

        input.sort(function(a, b){ return b.score - a.score;});

        var nextPlayer;
        var teamForNextPlayer;

        for (i = 0; i < max; i++){

            next();
            teams[teamForNextPlayer].push(nextPlayer);
            scores[teamForNextPlayer] += nextPlayer.score;
        }

        function getBest() {
            nextPlayer = input.splice(0, 1)[0]; //Best in list
        }
        function getWorst() {
            nextPlayer =  input.splice(input.length - 1, 1)[0]; //Worst in list
        }
        function next(){
            var counterA = teams["A"],
                counterB = teams["B"],
                scoreA = scores["A"],
                scoreB = scores["B"];

            if(counterA > counterB) { //B has less players than A
                teamForNextPlayer = "B";

                if(scoreB >= scoreA){
                    getWorst();
                }else{
                    getBest();
                }
            }
            else if(counterA < counterB) { //A has less players than B
                teamForNextPlayer = "A";
                if(scoreA >= scoreB){
                    getWorst();
                }else{
                    getBest();
                }
            }
            else //Same amount of players
            {
                getBest();
                teamForNextPlayer = (scoreA >= scoreB) ? "B" : "A";
            }
        }

        return {
            teamA: teams["A"],
            teamB: teams["B"],
            diff: Math.abs(scores["A"] - scores["B"]),
            scoreA: scores["A"],
            scoreB: scores["B"]
        };

    }
    return {
        setPlayers : setPlayers,
        createTeams: createTeams
    }
}());

If it's easier, you can pull the code from here.


texts:
I have a script used for installing few rpms depending on operating system type. Here in this example, the script will install packages on two system "centos" and "suse". The system names are listed in nodes.txt and read as an input while executing the script.

For example:

~]# cat systems.txt

centos
suse

~]# ./myscript.sh systems.txt

There are two scripts written which does the same purpose. One is written using "if-else" and other using "case".

When I use "if-else" condition script, the execution (i.e installation of rpms) completes much faster than using the "case" condition script. Both scripts does the same job, except that the control structure is different. I will have many hundreds of installation criteria listed in the script, and will add/remove new system types within systems.txt file.

Hence I am not sure which condition is better to choose, and considering my use case. Can someone help me know why does case script taking more time to execute when compared if-else? Any help/recommendations?

Below the case script which took 10 secs to complete.

#! /bin/bash

while read -d $'\n' -r node
do

# Each node has a unique id assigned and used along with install script
id=$(./name.sh -getid)

case $node in
   centos)
echo $(./install.sh --resourceId=$id --name=httpd)
echo $(./install.sh --resourceId=$id --name=gcc)
      ;;

    suse)
echo $(./install.sh --resourceId=$id --name=compact)
echo $(./install.sh --resourceId=$id --name=glib)
      ;;

   *)
        echo "#No resources found for the node"
    ;;
esac
done < "$1"

Below the if-else script which took 5 secs to complete:

#!/bin/bash
while read -d $'\n' -r node
do

# Each node has a unique id assigned and used along with install script
id=$(./name.sh -getid)

if [ $node == centos ]
then

echo $(./install.sh --resourceId=$id --name=httpd)
echo $(./install.sh --resourceId=$id --name=gcc)

elif [ $node == suse ]
then

echo $(./install.sh --resourceId=$id --name=compact)
echo $(./install.sh --resourceId=$id --name=glib)

else

echo "#No resources found for the node"

fi
done < "$1"


texts:
The purpose of this project is to generate an interactive logistic map. The user can click on the produced picture to magnify the picture at that point.
Here is the logistic map equation:

Here is my program:
public class LogisticMap {
    public static double returnLogisticEquation(double x, double r) {
        return r * x * (1 - x);
    }

    public static double ignoreFirstIterations(int numberOfIterations, double x, double r) {
        for (int i = 0; i < numberOfIterations; i++) {
            x = returnLogisticEquation(x, r);
        }
        return x;
    }

    public static void drawLogisticMap(int numberOfHorizontalPoints, int numberOfVerticalPoints, double leftOfRInterval, double rightOfRInterval, double x) {
        StdDraw.setYscale(0, 1);
        StdDraw.enableDoubleBuffering();
        double subintervalLength = (rightOfRInterval - leftOfRInterval) / numberOfHorizontalPoints;
        int numberOfIterations = 1000;
        for (double r = leftOfRInterval; r < rightOfRInterval; r += subintervalLength) {
            x = ignoreFirstIterations(numberOfIterations, x, r);
            for (int p = 0; p < numberOfVerticalPoints; p++) {
                x = returnLogisticEquation(x, r);
                StdDraw.point(r, x);
            }
        }
        StdDraw.show();
    }

    public static void interactiveLogisticMap(int numberOfHorizontalPoints, int numberOfVerticalPoints, double leftOfRInterval, double rightOfRInterval, double x) {
        StdDraw.setXscale(leftOfRInterval, rightOfRInterval);
        drawLogisticMap(numberOfHorizontalPoints, numberOfVerticalPoints, leftOfRInterval, rightOfRInterval, x);

        double r = 0;
        double y = 0;
        double scale = 0.05;

        while (true) {
            if (StdDraw.isMousePressed()) {
                r = StdDraw.mouseX();
                y = StdDraw.mouseY();

                double newLeftOfRInterval = r - scale;
                double newRightOfRInterval = r + scale;
                double belowRInterval = y - scale;
                double aboveRInterval = y + scale;

                StdDraw.setXscale(newLeftOfRInterval, newRightOfRInterval);
                StdDraw.setYscale(belowRInterval, aboveRInterval);
                StdDraw.clear();
                drawLogisticMap(numberOfHorizontalPoints, numberOfVerticalPoints, newLeftOfRInterval, newRightOfRInterval, x);

                scale /= 10;
            }
        }
    }

    public static void main(String[] args) {
        StdDraw.setCanvasSize(850, 850);

        int numberOfHorizontalPoints = 800;
        int numberOfVerticalPoints = 1000;
        double leftOfRInterval = 2.4;
        double rightOfRInterval = 4;
        double x = Math.random();

        interactiveLogisticMap(numberOfHorizontalPoints, numberOfVerticalPoints, leftOfRInterval, rightOfRInterval, x);
    }
}

StdDraw is a simple API written by the authors of the book Computer Science An Interdisciplinary Approach. I checked my program and it works. Here is one instance of it.
Output (actually a succession of outputs):

Is there any way that I can improve my program?
Thanks for your attention.


texts:
First time posting here, let me apologize ahead of time if this is not the correct format.. Anyway, I am new to programming and I am working on a school assignment to design a vehicle inventory system in Python (assignment details below). The code seems to be working as it should. I am questioning the 'update vehicle' function I defined outside of the class, whether it would make more sense to change to a class method. Or any other feedback anyone has. Thanks.
Create a final program that meets the requirements outlined below.

Assignment:
Create an automobile class that will be used by a dealership as a vehicle inventory program.  The following attributes should be present in your automobile class:

private string make
private string model
private string color
private int year
private int mileage

Your program should have appropriate methods such as:

constructor
add a new vehicle
remove a vehicle
update vehicle attributes

At the end of your program, it should allow the user to output all vehicle inventory to a text file.

class Automobile:

    def __init__(self):
        self.make = " "
        self.model = " "
        self.color = " "
        self.year = 0
        self.mileage = 0

    def add_vehicle(self):
        self.year = int(input("Enter year: "))
        self.make = input("Enter make: ")
        self.model = input("Enter model: ")
        self.color = input("Enter color: ")
        self.mileage = int(input("Enter mileage: "))

    def __str__(self):
        return('%d %s %s Color: %s Mileage: %d' %
              (self.year, self.make, self.model, self. color,
               self.mileage))

vehicle_list = []

def edit(vehicle_list):
    pos = int(input('Enter the position of the vehicle to edit: '))
    new_vehicle = car.add_vehicle()
    new_vehicle = car.__str__()
    vehicle_list[pos-1] = new_vehicle
    print('Vehicle was updated')

user=True
while user:
    print ("""
    1.Add a Vehicle
    2.Delete a Vehicle
    3.View Inventory
    4.Update Inventory
    5.Export Inventory
    6.Quit
    """)
    ans=input("What would you like to do? ")
    if ans=="1":
        car = Automobile()
        car.add_vehicle()
        vehicle_list.append(car.__str__())

    elif ans=="2":
        for i in vehicle_list:
            vehicle_list.pop(int(input('Enter position of vehicle to remove: ')))
            print('Successfully removed vehicle')
    elif ans=="3":
        print(vehicle_list)
    elif ans=="4":
        edit(vehicle_list)
    elif ans=='5':
        f = open('vehicle_inv.txt', 'w')
        f.write(str(vehicle_list))
        f.close()
    else:
        print('try again')


texts: How to shorten two methods with the same theme?

texts:
I have this code:

private void numWidth_ValueChanged(object sender, EventArgs e)
{
    if (ignoreChange) return; // Sometimes I only want to change the value without the event firing (like when undo-ing)

    PushUndoStack();

    int width = (int)numWidth.Value;

    foreach (Layer layer in doc.TileLayers)
        layer.Width = width;

    hscDoc.Maximum = doc.WidthInPixels;
    ClampScrollbarValue(hscDoc);
}

private void numHeight_ValueChanged(object sender, EventArgs e)
{
    if (ignoreChange) return;

    PushUndoStack();

    int height = (int)numHeight.Value;

    foreach (Layer layer in doc.TileLayers)
        layer.Height = height;

    vscDoc.Maximum = doc.HeightInPixels;
    ClampScrollbarValue(vscDoc);
}

They are both very similar yet I can't really think of a good way to combine the two. This happens several times in my program and the lines of code are really adding up. I suppose I could use reflection but is it overkill? Can anyone think of a better way?

This is just an example. This happens quite a few times in my program where functions are very similar but cannot be easily refactored in to a generic method.


texts:
To generate a password, I generate a key using RNGCryptoServiceProvider. The key is 9 alphanumeric characters long into which I insert a single non-alphanumeric character for a full length of 10 characters.

Having a mix of Uppercase, lowercase, numbers and symbols and being 10 characters long, as a plain text password (which you'd enter when logging in somewhere), this password should be more than adequate for most situations.

// used for more than just generating a password
public static string CreateKey(int length)
{
    string Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdejghijklmnopqrstuvwxyz1234567890";
    StringBuilder Sb = new StringBuilder();

    using (RNGCryptoServiceProvider Rng = new RNGCryptoServiceProvider())
    {
        byte[] Buffer = new byte[sizeof(uint)];

        while (length-- > 0)
        {
            Rng.GetBytes(Buffer);
            uint N = BitConverter.ToUInt32(Buffer, 0);
            Sb.Append(Chars[(int)(N % (uint)Chars.Length)]);
        }
    }

    return Sb.ToString();
}

public static string CreatePasswordString()
{
    string Chars = @"~`!@#$%^&*()\/',.?;:|";
    var RNG = new Random();

    // Select a character to insert into the password
    string Character = new String(Enumerable.Repeat(Chars, 1).Select(s => s[RNG.Next(s.Length)]).ToArray());

    return CreateKey(9).Insert(RNG.Next(9), Character);
}

This generates a password which is then hashed in my application using bcrypt as per below:

public static string CreatePassword(string password)
{
    byte[] PasswordBytes = Encoding.ASCII.GetBytes(password);

    return Crypter.Blowfish.Crypt(PasswordBytes);
}

I can then validate the input at login more or less with this function - I haven't tested this code since I'm writing it for the first time for this question.

public static bool ValidatePassword(string emailAddress, string password)
{
    var User = db.Users.FirstOrDefault(x => x.EmailAddress == emailAddress);

    if (User == null) return false;

    return Crypter.Blowfish.CheckPassword(password, User.Password);
}

I used to use PBKDF2 but I was informed that bcrypt is better so here we are. While I understand the rule "never use your own auth", is this code likely to provide decent security?

What sort of vulnerabilities are present in implementing this system for security?


texts:
For context, I worked on the LeetCode May 2020 Challenge Week 3 Day 1. The challenge was described as this:

  Given a string, sort it in decreasing order based on the frequency of
  characters.

  Example 1:

  Input: "tree"

  Output: "eert"

  Explanation: 'e' appears twice while 'r' and 't' both appear once. So
  'e' must appear before both 'r' and 't'. Therefore "eetr" is also a
  valid answer.

  Example 2:

  Input: "cccaaa"

  Output: "cccaaa"

  Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also
  a valid answer. Note that "cacaca" is incorrect, as the same
  characters must be together.

  Example 3:

  Input: "Aabb"

  Output: "bbAa"

  Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
  Note that 'A' and 'a' are treated as two different characters.

Anyways, I looked up some popular solutions. One was to get the frequency of each character and sort, and the other was the use a heap. I liked both of these solutions, but I wanted to make one where there was no sorting.

My solution involved an idea of an ArrayList of "tiers," where the index of the tier represents the frequency. Each tier consists of an ArrayList containing the characters which the corresponding frequency. As letters increase in frequency, the higher frequency tier they move up. I also used a HashMap to keep track of which frequency tier each character was in. Upon finishing iterating through the whole string, I simply use a StringBuilder to append the letters starting at the bottom tier, reverse the StringBuilder, then return the String. I was hoping someone could give me pointers (ha, code pun) on optimizing/modifying this approach without including any kind of sorting. Below is the functional code:

public static String frequencySort(String s) {
        if (s.length() <= 1) return s;

        ArrayList<ArrayList<Character>> tieredFreq = new ArrayList<>(); // stores characters at their proper frequency "tier"
        HashMap<Character, Integer> tierOfChars = new HashMap<>(); // maps the characters to their current frequency tier
        tieredFreq.add(null); // tier 0

        for (char c : s.toCharArray()) {
            tierOfChars.put(c, tierOfChars.getOrDefault(c, 0) + 1); // add char or increment the tier of the character
            int i = tierOfChars.get(c); // i = tier of the character
            if (tieredFreq.size() <= i) tieredFreq.add(new ArrayList<>()); // if not enough tiers, add a new tier
            if (i > 1) tieredFreq.get(i - 1).remove(new Character(c)); // if c exists in previous tier, remove it
            tieredFreq.get(i).add(c); // add to new tier
        }

        StringBuilder result = new StringBuilder();
        for (int i = 1; i < tieredFreq.size(); i++) { // iterate through tiers
            ArrayList<Character> tier = tieredFreq.get(i); // get tier
            for (Character c : tier) { // for each char in tier, append to string a number of times equal to the tier
                for (int j = 0; j < i; j++) result.append(c);
            }
        }

        result.reverse(); // reverse, since result is currently in ascending order
        return result.toString();
    }


texts: Fetch entire table from database after validating the table name

texts:
I'm creating a database class. It's part academic and part something I may show in an interview.

The purpose of this method is to accept a table name as a parameter, check if the PDO Object has been created (this is in an earlier method), check if the table is in the database as to white list the table for going further in the script, and also to check if the parameter contains any characters that MySQL does not support for unquoted identifiers. If it passes then the table is returned.

<?php
class DatabaseClass{
...
public static function getTable($tablename = ''){
    if(!isset(self::$pdo)){
        trigger_error('Error: '.__CLASS__.'::'.__METHOD__.'() requires a database connection.',E_USER_ERROR);
        return false;
    }
    $whitelist = self::$pdo->query('SHOW TABLES');
    if(!in_array($tablename, $whitelist->fetchAll(PDO::FETCH_ASSOC)) || preg_match('[^0-9,a-z,A-Z$_]',$tablename)){
        /*If tablename is not in the database or if it contains illegal characters*/
        return false;
    }else{
        $tbl = self::$pdo->query('SELECT * FROM `'.$tablename.'`');
        return $tbl->fetchAll(PDO::FETCH_ASSOC);
    }
}
...


texts: SQL-like syntax to sort and filter a collection

texts:
I was helping someone on SO with an assignment to create a macro that accepts an SQL-like syntax, and optionally sorts and filters a collection. I realized that while their instructor is insisting on them using macros, macros aren't actually required at all. I decided to try my hand at creating a function that solves the assignment (roughly).

This is my first stab at it. It's not great yet (there's no way to pick between ascending and descending sort order for example), but it's a first step.

An example of its usage:

(def test-db [{:id 1, :name "A"},
              {:id 0, :name "B"},
              {:id 3, :name "C"},
              {:id 2, :name "D"},
              {:id 4, :name "E"}])

(select [:name] :from test-db :where [:id < 3] :order-by :id)
=> ("B" "A" "D")

Considering this only took me like 20 minutes to write, I'm pretty happy with it. I do have a few major concerns though:

I dislike how I'm turning the variadic parameters into a map. Right now, I'm using

(let [arg-map (into {} (map vec (partition 2 args))) ...

But this seems overly complicated. It doesn't seem like lazy-seqs can be treated as MapEntries like vectors can, so (map vec ... is necessary to allow the conversion. A better way here would be appreciated.
Originally I had :from as part of args, but it's a necessary field, so it seemed messy to allow it to be optional, only to check for it's existence in the function. I made it a required argument, but that made it so the second argument to select is entirely useless and discarded, which also seems messy.
Any other suggestions would be appreciated.

(defn- where
  "Turns a vector of [key comparator compare-value] into a predicate that filter can use."
  [arg-vec]
  (let [[k f comp-arg] arg-vec]
    (fn [elem] (f (k elem) comp-arg))))

(defn select
  "Selects the given keys from the \"database\", filtered by the :where clause, and ordered by the :order-by key.

  Example:
  (select [:id] :from [{:id 1} {:id 2}] :where [:id > 0] :order-by :id)"
  [selection _ from & args]
  (let [arg-map (into {} (map vec (partition 2 args)))
        {where-vec :where, order-key :order-by} arg-map

         filt-ordered
         (cond->> from
           where-vec (filter (where where-vec))
           order-key (sort-by order-key))]

      (mapcat #(map % filt-ordered) selection)))