Load excel sheet to data frame I have a bare-bones example of how I plan to load excel sheets into pandas data frames. However, the code runs unexpectedly slow. I'm open to suggestions on ways I can speed this up, even converting the source files to a different file format. Anything to make it snappier because I will need a loop to do this several times over multiple sheets and workbooks. Thank you.

import os
import pandas as pd

path_to_data_files = 'C:/DataArchive/'
files = sorted(os.listdir(path_to_data_files), reverse=True)

file = pd.ExcelFile(path_to_data_files + files[0])

sheet_names = file.sheet_names

df = file.parse(sheets[0])

There are several ways you can go about doing this.

Use pandas.read_excel
Manually convert excel workbook to csv file then use pandas.read_csv
Use Python code to convert excel workbook to csv file then use pandas.read_csv

The third method is your best approach. It's the fastest.

Here is my excel workbook

1

df1 = pandas.read_excel('workbook.xlsx')
print(df1)

Out

  col1    col2     col3        col4
0   I   should       be  completing
1   my  linear  algebra    homework

2

I named the .csv file 'workbook.csv'

df2 = pandas.read_csv('workbook.csv')
print(df2)

Out

  col1    col2     col3        col4
0   I   should       be  completing
1   my  linear  algebra    homework

3

import csv
import xlrd
with xlrd.open_workbook('workbook.xlsx') as wb:
    sh = wb.sheet_by_index(0)
    with open('workbook.csv', 'w', newline="") as csv_file:
        col = csv.writer(csv_file)
        for row in range(sh.nrows):
            col.writerow(sh.row_values(row))
df3 = pandas.read_csv('workbook.csv')
print(df3)

Here is the .csv produced, calle

col1,col2,col3,col4
I,should,be,completing
my,linear,algebra,homework

And then the subsequent dataframe

  col1    col2     col3        col4
0   I   should       be  completing
1   my  linear  algebra    homework

VERDICT

All the outputs for each method is the same but method 3 is the fastest. This means you should import csv and xlrd to convert each of your xlsx files to csv files and then use read_csv. You can use os to get into your specific directories. Add for loops for each file for solution 3.

NOTE

Test method 1 versus 2 for yourself because I am getting somewhat inconsistent results using the timeit module and writing

start = timeit.timeit()
# code
end = timeit.timeit()
print(f"Time {end - start} {df}")

but I am not sure if I am using it correctly. So, at the very least, try the first and last methods for yourself and see which ones go faster.


Get all objects which contains any given array of Enums What this does?:

Interactions is an Enum whereas Interactable is an interface (not @Functional Interface). Every Interactable has a list of Interactions that it can do. The below code snippet, filters out all the objects that contains any of the provided Interactions. It does not check for all Interactions, so if any of the given Interactions found, it adds the object in interactableList. Once done iterative over the List, sends it back to the caller for further processing.

public List<Interactable> getObjectsByInteractions (final Interactions[] interactions) {
    final List<Interactable> interactableList = new ArrayList<>();
    for (Interactable object : objects) {
        List<Interactions> objectInteractions = object.getInteractions();
        for (Interactions interactions1 : interactions) {
            if (objectInteractions.contains(interactions1)) {
                interactableList.add(object);
                break;
            }
        }
    }
    return interactableList;
}

Concern:

Right now, I am using pre Java 8 code style to achieve the results. Since, it's the time of Java 8, I would request the reviewers to suggest Java 8 style.

There is nothing particularly wrong with your current code, although I have a couple of comments:

The name interactions1 of the local variable is slightly confusing.
Instead of having a break, you could have a separate method that determines if a given Interactable contains as interactions one of the given interactions.

With the Stream API, you could have the following:

public List<Interactable> getObjectsByInteractions(final Interactions[] interactions) {
    return objects.stream()
                  .filter(object -> Arrays.stream(interactions).anyMatch(object.getInteractions()::contains))
                  .collect(Collectors.toList());
}

This creates a Stream<Interactable> of your objects. It then filters out all the unwanted object: for that a Stream<Interactions> of the given interactions is created and anyMatch tells whether object.getInteractions() contains one of those interactions. Finally, the elements are collected into a list.


Listing sales with a matching quantity Ive been sitting here for the past 20 minutes trying to make this simple/tiny function more 'readable' and 'clean'. Am I overthinking this or am I missing some major tips that could help me out?

string findSameSales (int numSold, int salesArray[], string namesArray[])
 {
  string ssList = " ";
  for (int counter = 0; counter <= NUM_OF_POS; counter++)
    {
      if (numSold == salesArray[counter])
        {
         if (ssList == " ")
           ssList = namesArray[counter];
         else
           ssList += (", " + namesArray[counter]);
        }
      else;
    }

  return ssList;
 }

How about using std::accumulate():

Live Demo

#include <string>
#include <iterator>
#include <algorithm>
#include <numeric>

const int NUM_OF_POS = 10;

std::string findSameSales (int numSold, const int salesArray[], const std::string namesArray[])
{
    int index = -1;
    return std::accumulate(salesArray, salesArray + NUM_OF_POS, std::string(" "), [numSold, namesArray, &index](std::string sales, int sold) { index++; return sold == numSold ? sales + " , " + namesArray[index] : sales; });
}

Alternative on more lines:

std::string findSameSales (int numSold, const int salesArray[], const std::string namesArray[])
{
    int index = -1;
    auto accumulator = [numSold, namesArray, &index](std::string sales, int sold)
    {
        index++;
        return sold == numSold ? sales + " , " + namesArray[index] : sales;
    }
    return std::accumulate(salesArray, salesArray + NUM_OF_POS, std::string(" "), accumulator);
}

I really believe you should use STL algorithms for these kinds of things. Only roll your own loop etc. when you cannot use them. But this for example is almost the same as in the C++ reference docs so almost a "model case".


Updates list in haskell to remove duplication The task in question allows a user to re-rate a film such that only the latest rating from the user should remain in the database.
Initially I solved this problem in a very basic manor?

This was my result:

type Rating = (String, Int)
type Film = (String, String, Int, [Rating])
--Example ("Blade Runner","Ridley Scott",1982, [("Amy",5),("Bill",8)])

where the functions:

--Find selected film, isolate into new List
getFilm :: String -> [Film] -> [(Film)]
getFilm search aFilm = [(title,dir,year,ratings) | (title,dir,year,ratings) <- aFilm, search == title]

--Update the new film and pull details for amendment, STORE
pullTitle :: [(Film)] -> String
pullTitle [(title,_,_,_)] = title

pullDirector :: [(Film)] -> String
pullDirector [(_,director,_,_)] = director

pullYear :: [(Film)] -> Int
pullYear [(_,_,year,_)] = year

pullRatings :: [(Film)] -> [Rating]
pullRatings [(_,_,_,rating)] = rating

newRatings :: [Rating] -> Rating -> [Rating]
newRatings oldRatings (newUser,newRate) = [(user,rate) | (user,rate) <- oldRatings, user /= newUser] ++ [(newUser,newRate)]

--Database without selected film
updateDatabase :: String -> [Film] -> [(Film)]
updateDatabase search aFilm = [(title,dir,year,ratings) | (title,dir,year,ratings) <- aFilm, search /= title]

--Adds new film to a database
updatedFilm :: String -> String -> Int -> [Rating] -> [Film] -> [Film]
updatedFilm name director yearOfRel ratings database = database ++ [(name,director,yearOfRel,ratings)]

--Add new film to updated Database
formulateFilm :: [(Film)] -> [(Film)] -> Rating -> [(Film)]
formulateFilm soloFilm updatedFilms updateRating = updatedFilm (pullTitle soloFilm) (pullDirector soloFilm) (pullYear soloFilm) (newRatings (pullRatings soloFilm) updateRating) updatedFilms

--Compiling to for finalcome
rateMovie :: String -> Rating -> [Film] -> [(Film)]
rateMovie mTitle newRating oldDatabase = formulateFilm (getFilm mTitle oldDatabase) (updateDatabase mTitle oldDatabase) newRating

I have changed the following functions to make use of filters:

getFilm :: String -> [Film]
getFilm search = filter(\(title,_,_,_) -> search == title) testDatabase

updateDatabase :: String -> [Film]
updateDatabase search = filter(\(title,_,_,_) -> search /= title) testDatabase

Could someone advise me on how I would use maps to get the selected films data from getFilm :: String -> [Film], similar to the (pull*) functions?

It is better to use records instead of tuples here:

data Rating = Rating
  { user :: String
  , rate :: Int
  } deriving Show

data Film = Film
  { title    :: String
  , director :: String
  , year     :: Int
  , ratings  :: [Rating]
  } deriving Show

Thus you get self documenting code and all of pull* functions for free (for each field compiler generates accessor function with the same name).

This also leads to more concise implementation of other functions:

-- Find films by name
getFilm :: String -> [Film] -> [Film]
getFilm search = filter ((== search) . title)

Note that in Haskell there is no single element tuple, so parentheses around Film are redundant ([Film] but not [(Film)]).

newRating :: Rating -> [Rating] -> [Rating]
newRating r = (r :) . filter ((/=user r) . user)

I switched arguments in newRating because this allows to define function more concisely and it is also correlates with update/insert from Data.Map: they have collection as a last argument.

Now it is possible to skip directly to rateMovie and implement it in couple of lines:

rateMovie :: String -> Rating -> [Film] -> [Film]
rateMovie mTitle nRating database
  = [m {ratings = newRating nRating (ratings m)} | m <- matchingMovies]
  ++ database'
  where
    (matchingMovies, database') = partition ((==mTitle).title) database

(Btw, why "movie"? we were talking about "films" all the way.)

I'm using partition from Data.List to extract matching movie(s) from database.

Also there is funny syntax I'm using to update movies:

m {ratings = ...}

You can read more about it here.

And of course it is better to use Data.Map instead of simple lists if the code is full of lookups.


HTML5 semantic layout (div, article, section) and explicit identifiers I'm writing a markup for:

And I've split it for these sections:

Is it semantically correct(div, section, article) and are my identifiers explicit?

#logo → h1

Your

 should be a h1, otherwise the document outline wouldn't be correct:

See https://stackoverflow.com/a/14920215/1591669 for an explanation.

#banner → header or aside

If your

 doesn't contain main content, it should go in an aside element, or, if it can be understood as part of the header (probably on each page of the site), in the header element.

#main → section (or article)

Instead of

 you could use a sectioning element here. I assume your div contains a heading ("Welcome, dear visitor!"), so you have something like an implict section anyhow. Why not make it explicit? So use a section instead of the div (depending on the actual content, article might be suitable instead).

#content > aside → section

I'd say on the front page the testimonials could be considered part of the main content (in the end it depends on the real content/context), so instead of aside you could use section then.

Each single testimonial should be in its own article, of course.

#extra > article → section

I don't think article elements in the footer are suitable for that kind of content (unless your actual page contains something different). (Only the newsletter form could possibly get article instead of section, but that's not that clear; personally I'd use section for it, too).

So, I'd go with section here. If the contact details listed under "Address" are relevant for the whole page, you should use the address element, too.

Address

      <address>…</address>


Initializing object by settings implemented as a class Here is the story.

We have the BankTerminalSettings class.

It has many properties:

public class BankTerminalSettings {
    public bool IsEnabled { get; set; }
    public string IPAddress {get; set;}
    public ushort TcpPort {get; set; }
    public List<string> Zombies {get; set;}

    //and many other properties
}

And we have a class which takes BankTerminalSettings as a parameter of it's constructor.

public class BankTerminal {
    public BankTerminal(BankTerminalSettings terminal, int clientId) {
        ValidateBankTerminalSettings(terminal);

        terminalSettings = terminal;
        this.clientId = clientId;
    }
}

The thing is that the BankTerminal uses only three of all those properties in that domain config class named BankTerminalSettings.
It's a temptation just to pass the whole instace of the BankTerminalSettings, but the caller can incidentally change those properties which are relevant for the BankTerminal. That can cause very subtle bugs.

What would you recommend?
To replicate the BankTerminalSettings before passing it's instance?
To replicate the BankTerminalSettings in the constructor of the BankTerminal?
To pass only those parameters which are truely needed by the BankTerminal?

It depends on whether you want to handle config updates or not. In your case I guess you just want to work with data at constructing point. There are few options to do this:

Make copy of your settings before they are passed and use BankTerminalSettings inside the BankTerminal (as was considered). But personally I dont like the idea there are different BankTerminalSettings passing around.
Better approach would be just to inialize your internal fields with config settings, i.e. to copy settings of BankTerminalSettings to BankTerminal

Also I'm worried with the fact BankTerminalSettings contain more properties than is needed for BankTerminal. Maybe BankTerminalSettings should get another name? Anyway, I would create interface IBankTerminalSettings that contain only properties needed by BankTerminal and pass it to BankTerminal constructor


Cash register allowing all coins I had to build a cash register that included a Coin class that allowed for all types of coins to be used. Please note that for this, no control structures can be used and no data structures such as arrays, lists, and what not. Any constructive criticism is welcome.

public class CashRegisterTest
{
    //Test the methods in CashRegister class
    //@param args not used
    public static void main(String[] args)
    {
        //European Coins
        final double EURO = 1;
        final double FIFTY_CENT = .5;
        final double TWENTY_CENT = .2;
        final double TEN_CENT = .1;
        final double FIVE_CENT = .05;
        final double ONE_CENT = .01;

        //American Coins
        final double DOLLAR = 1;
        final double QUARTER = 0.25;
        final double DIME = 0.10;
        final double NICKEL = 0.05;
        final double PENNY = 0.01;

        CashRegister register = new CashRegister();
        register.recordPurchase(10.99);
        register.recordPurchase(10.01);
        register.enterPayment(20, new Coin(EURO));
        register.enterPayment(2, new Coin(FIFTY_CENT));

        System.out.println(register.returnChange());

        CashRegister registerTwo = new CashRegister();
        registerTwo.recordPurchase(10.99);
        registerTwo.recordPurchase(10.01);
        registerTwo.enterPayment(20, new Coin(DOLLAR));
        registerTwo.enterPayment(4, new Coin(QUARTER));

        System.out.println(register.returnChange());
    }
}

public class CashRegister
{
    private double purchase;
    private double payment;

    private int items;

    //Construct a cash register with no money.
    public CashRegister()
    {
        payment = 0;
        purchase = 0;
        items = 0;
    }

    //Records the purchase price of an item
    //@param amount the price of the purchased item
    public void recordPurchase(double amount)
    {
        purchase += amount;
        items++;
    }

    //Enter payment recieved.
    //@param amount the amount of coins given
    //@param value the coin that has been given.
    public void enterPayment(int amount, Coin value)
    {
        payment += amount * value.getValue();
    }

    //Compute the change due and set the machine for the next customer.
    //@return change the amount due to the customer.
    public double returnChange()
    {
        return payment - purchase;
    }

    //Get the item count
    //@return items the amount of items in this transaction
    public int getItemCount()
    {
        return items;
    }
}

public class Coin
{
    private double value;

    public Coin(double value)
    {
        this.value = value;
    }

    public double getValue()
    {
        return value;
    }
}

You really shouldn't use double for currency. It's probably fine for this, but in a real world application, the accuracy problems you'd experience would be terrible to deal with. It's recommended that you use the currency class for money.

Also, just a small note. I like your brace style, but most Java folks use a different convention. Consistency within a code base is most important, but folks get kind of crazy about this kind of trivial stuff. Best to do as the Romans when in Rome.

public Coin(double value){
    this.value = value;
}


Create a folder and perform a SaveAs I have this code that is working as intended. Since I am still learning VBA and coding, I was wondering if anyone could look at this at let me know if there is another way to write this. This is part of an Add-In I created and is used by several other people (meaning that I installed the Add-In onto their PCs).

Sub Ex()
If InStr(LCase$(ActiveWorkbook.name), "extract") > 0 Then
    Exit Sub
Else
     Dim MyDir As String, fn As String
     MyDir = CreateObject("WScript.Shell").SpecialFolders("MyDocuments") & "\Extract Files" ' change this to valid path
     If Len(Dir(MyDir, vbDirectory)) = 0 Then MkDir MyDir
     fn = MyDir & "\Extract - " & Format(Now, "mm-dd-yyyy hh_mm")
     ActiveWorkbook.SaveAs Filename:=fn, FileFormat:=xlOpenXMLWorkbook
End If
End Sub

I had a problem with the code creating a new file each time the custom menu button (which is the trigger for the add-in and has other tools that are used on this workbook) was activated, so I added this to prevent that from occurring:

If InStr(LCase$(ActiveWorkbook.name), "extract") > 0 Then
        Exit Sub
    Else

Please let me know if there is any room for improvement of the way this is constructed.

You haven't mentioned exactly what triggers this code, but it might run on any open workbook, even if that workbook is confidential to the active user. You might want to consider checking if the activeworkbook is actually a workbook that you want to save. For example, you could check for a document property or a sheetname.

I've made a few changes

The InStr function can be case-insensitive, so you don't need to use the LCase statement

The FileSystemObject makes it easier to work with files and folders, than using MkDir and Dir.

The FileSystemObject has a BuildPath method that makes building paths easier than using concatenation and worrying about whether you need a backslash

Your function and variables were a little ambiguously named... Better to use names that have explicit meanings.

Your SaveAs file name uses mm-dd-yyyy format, but you'll probably be better off with yyyymmdd as your files will then sort alphabetically and chronologically (and it's an ISO standard)

Your SaveAs file name is missing a file extension. It's good practice to add an extension, even if your Explorer settings don't show them, as extensions help Windows to determine which application to use, and they help users identify the files they need to keep/discard.

 Sub ExtractFile()
  'Add a reference to Microsoft Scripting Runtime
  If InStr(1, ActiveWorkbook.Name, "extract", vbTextCompare) > 0 Then
    Exit Sub
  Else
    Dim oFSO As Scripting.FileSystemObject
    Dim folMyDocs As Scripting.Folder
    Dim sExtractsPath As String
    Dim sFilePath As String

    Set oFSO = New Scripting.FileSystemObject
    Set folMyDocs = oFSO.GetFolder(CreateObject("WScript.Shell").SpecialFolders("MyDocuments"))
    sExtractsPath = oFSO.BuildPath(folMyDocs, "Extract Files")
    If Not oFSO.FolderExists(sExtractsPath) Then
      oFSO.CreateFolder sExtractsPath
    End If
    'sFilePath = oFSO.BuildPath(sExtractsPath, Format(Now, "mm-dd-yyyy hh_mm"))
    sFilePath = oFSO.BuildPath(sExtractsPath, Format(Now, "yyyymmdd-hhmmss") & ".xlsx")
    ActiveWorkbook.SaveAs Filename:=sFileName, FileFormat:=xlOpenXMLWorkbook
  End If

End Sub


Index Match with multiple columns using input boxes I find this script handy for preparing ad-hoc reporting. Using two sets of unique identifiers, it allows you to lookup multiple columns of data with the Index Match function. I welcome any feedback or suggestions for improvement.

Sub MatchMaster_PRO()

'Peter Domanico (June 2018)
'this script helps simplify the use of Excel's Index Match function
'place this script in your personal macro workbook and assign it to a button
'use it to pull data between two worksheets that share unique identifiers

'dim ranges
    Dim ValuesToPull As Range
    Dim TargetIDs As Range
    Dim SourceIDs As Range
    Dim MyRange As Range

'dim worksheets
    Dim Source1 As Worksheet
    Dim Target1 As Worksheet
    Dim Source2 As Worksheet
    Dim Target2 As Worksheet

'input box dims
    Dim Prompt1 As String
    Dim Prompt2 As String
    Dim Prompt3 As String
    Dim Prompt4 As String
    Dim Title1 As String
    Dim Title2 As String
    Dim Title3 As String
    Dim Title4 As String

'set prompts
    Prompt1 = "Select values to pull (1 or more columns)"
    Prompt2 = "Select unique IDs on target sheet (1 column only)"
    Prompt3 = "Select unique IDs on source sheet (1 column only)"
    Prompt4 = "Select any range on target sheet"

'set titles
    Title1 = "Source Sheet"
    Title2 = "Target Sheet"
    Title3 = "Source Sheet"
    Title4 = "Target Sheet"

'error handling
    On Error GoTo OuttaHere

'input boxes
    Set SourceIDs = Application.InputBox(Prompt3, Title3, Type:=8)
    Set Source1 = SourceIDs.Worksheet
    SourceIDcolumn = SourceIDs.Column
    LastSourceID = Source1.Cells(Rows.Count, SourceIDcolumn).End(xlUp).Row
    Source1.Activate

    Set ValuesToPull = Application.InputBox(Prompt1, Title1, Type:=8)
    Set Source2 = ValuesToPull.Worksheet
    LastValue = LastSourceID
    Source2.Activate

    Set TargetIDs = Application.InputBox(Prompt2, Title2, Type:=8)
    Set Target1 = TargetIDs.Worksheet
    TargetIDcolumn = TargetIDs.Column
    LastTargetID = Target1.Cells(Rows.Count, TargetIDcolumn).End(xlUp).Row '<~~ also use this for MyRange
    Target1.Activate

    Set MyRange = Application.InputBox(Prompt4, Title4, Type:=8)
    Set Target2 = MyRange.Worksheet
    MyColumn = MyRange.Column
    Target2.Activate

'convert input to Range Cells format
    With Source1
        Set SourceIDs = .Range(.Cells(1, SourceIDcolumn), .Cells(LastSourceID, SourceIDcolumn))
    End With
    With Target1
        Set TargetIDs = .Range(.Cells(1, TargetIDcolumn), .Cells(LastTargetID, TargetIDcolumn))
    End With

    Dim rng As Range
    For Each rng In ValuesToPull.Columns
        ValuesColumn = rng.Column
        NextColumn = Target2.Cells(1, Columns.Count).End(xlToLeft).Column + 1
        With Source2
            Set ValuesToPull = .Range(.Cells(1, ValuesColumn), .Cells(LastValue, ValuesColumn))
        End With
        With Target2
             Set MyRange = .Range(.Cells(1, NextColumn), .Cells(LastTargetID, NextColumn))
        End With
        MyRange = Application.index(ValuesToPull, Application.Match(TargetIDs, SourceIDs, 0))
    Next rng

OuttaHere:
    ActiveWorkbook.ActiveSheet.Columns.AutoFit

End Sub

VBE -> Menu Bar -> Tools -> Options

I recommend turning off [ ] Auto Syntax Check and turning on [x] Require Variable Declaration

Turning off Auto Syntax Check will stop those annoying messages from popping up when you are writing code.  The VB Editor highlights syntax errors in red anyway.  The messages do nothing but break the workflow and slow you down.

Require Variable Declaration inserts Option Explicit at the top of newly created code modules.  Option Explicit requires that all variables be declared. Ideally, all variable should be declared and strongly typed.

Declaring Variables

These variables were not declared:

Dim LastSourceID As Long, LastTargetID As Long, LastValue As Long, MyColumn As Long, NextColumn As Long, TargetIDcolumn As Long, ValuesColumn As Long, SourceIDcolumn As Long

I prefer grouping my variables (at the top of the procedure), roughly 1 Dim statement per datatype. I do not like having to scroll to see what the code is doing.

The first thing that stands out is that the Title and Prompt variables are constant values and should be declared as Constants.

'set prompts
Const Prompt1 As String = "Select values to pull (1 or more columns)"
Const Prompt2 As String = "Select unique IDs on target sheet (1 column only)"
Const Prompt3 As String = "Select unique IDs on source sheet (1 column only)"
Const Prompt4 As String = "Select any range on target sheet"

'set titles
Const Title1 As String = "Source Sheet"
Const Title2 As String = "Target Sheet"
Const Title3 As String = "Source Sheet"
Const Title4 As String = "Target Sheet"

Constants can also be grouped but I usually don't because it can make them difficult to reference and modify.

'set prompts
Const Prompt1 As String = "Select values to pull (1 or more columns)",Prompt2 As String = "Select unique IDs on target sheet (1 column only)", Prompt3 As String = "Select unique IDs on source sheet (1 column only)",Prompt4 As String = "Select any range on target sheet"

'set titles
Const Title1 As String = "Source Sheet", Title2 As String = "Target Sheet", Title3 As String = "Source Sheet",Title4 As String = "Target Sheet"

Helper Variables

"Helper Variables" are great when they are helpful.  Many times they are just extra clutter that you have to work through.

Prompt1 is helpful because of the length of the string and these is something that you will probably consider modifying in the future.

Const Prompt1 As String = "Select values to pull (1 or more columns)"

Title1 is pretty short and easily modified where it is used.  I would not have bothered with it.

Set ValuesToPull = Application.InputBox(Prompt1, "Source Sheet", Type:=8)

I personally would save the space and use one of the following:

Set ValuesToPull = Application.InputBox("Select values to pull (1 or more columns)", "Source Sheet", Type:=8)

Set ValuesToPull = Application.InputBox( _
                   "Select values to pull (1 or more columns)", _
                   "Source Sheet" _
                   , Type:=8)

Set ValuesToPull = Application.InputBox( _
                   Prompt:="Select values to pull (1 or more columns)", _
                   Title:="Source Sheet" _
                   , Type:=8)

Are Source1, Target1, SourceIDcolumn, and LastSourceID really needed?

I like to use the Optometrist Analogy when reviewing code.

Which is clearer, Code 1 or Code 2?

Code 1:

With Source1
    Set SourceIDs = .Range(.Cells(1, SourceIDcolumn), .Cells(LastSourceID, SourceIDcolumn))
End With

Code 2:

With SourceIDs.Worksheet
    Set SourceIDs = .Range(.Cells(1, SourceIDcolumn), .Cells(LastSourceID, SourceIDcolumn))
End With

Which is clearer, Code 2 or Code 3?

Code 3:

Set ValuesToPull = Intersect(SourceIDs.EntireRow, ValuesToPull.EntireColumn)

For me Code 3 is clearer.  But not everyone sees code the same way.  You should use the one that is easiest for you to read.  Note:  If you didn't choose Code 3, you might want to consider Lasik.

Repeated Code Patterns

Repeated code patterns in a subroutine is a sign that potions of the code can and probably should be extracted into a separate subroutine.  This will make both the main and extracted code easier to read, debug, and modify.

Public Function getInputRange(Prompt As String, Title As String, Optional AllowMultipleColumns As Boolean) As Range
    Dim Target As Range
    Set Target = Application.InputBox(Prompt, Title, Type:=8)

    If Target Is Nothing Then Exit Function
    If Target.Columns.Count > 1 And Not AllowMultipleColumns Then Exit Function

    With Target.EntireColumn
        Set Target = Range(.Cells(1, 1), .Cells(.Rows.Count).End(xlUp))
    End With

    Set getInputRange = Target
End Function

Other Considerations

Are there Column Headers?
    hasColumnHeader = MsgBox("Do the Ranges Contain Column Headers?", vbYesNo, "Column Header")

Rows.Count should be qualified to the same worksheet the Target1.

Target1.Cells(Rows.Count

Performance

Turning off Application.Application.ScreenUpdating and setting Calculation = xlCalculationManual will greatly improve the performance of code that modify the formats and values of worksheets.

Public Sub SpeedBoost(TurnOn As Boolean)
    With Application
        .Calculation = IIf(TurnOn, xlCalculationManual, xlCalculationAutomatic)
        .ScreenUpdating = Not TurnOn
    End With
End Sub

Reading values from an array is a little faster than reading values from a range.  Writing multiple values from an array to a range in 1 operating is much faster than multiple writes.

Dictionaries are much faster than Application.Match. Reference:Analyst Cave: EXCEL VLOOKUP VS INDEX MATCH VS SQL VS VBA


Encode and Decode TinyURL The task

is taken from leetcode

  TinyURL is a URL shortening service where you enter a URL such as
  https://leetcode.com/problems/design-tinyurl and it returns a short
  URL such as http://tinyurl.com/4e9iAk.

  Design the encode and decode methods for the TinyURL service. There is
  no restriction on how your encode/decode algorithm should work. You
  just need to ensure that a URL can be encoded to a tiny URL and the
  tiny URL can be decoded to the original URL.

My solution

const url = {};
const ALPHANUMERIC = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const PREFIX = 'http://tinyurl.com/';
/**
 * Encodes a URL to a shortened URL.
 *
 * @param {string} longUrl
 * @return {string}
 */
function encode(longUrl) {
  let id = createIdOfSize(6);
  while(url[id]) {
    id = createIdOfSize(6);
  }
  url[id] = longUrl;
  return PREFIX + id;
};

function createIdOfSize(n) {
  let i = n;
  let id = '';
  while(i-- > 0) {
    id += ALPHANUMERIC[(Math.random() * ALPHANUMERIC.length) | 0];
  }
  return id;
};
/**
 * Decodes a shortened URL to its original URL.
 *
 * @param {string} shortUrl
 * @return {string}
 */
function decode(shortUrl) {
  return url[shortUrl.split(PREFIX)[1]];
};

/**
 * Your functions will be called as such:
 * decode(encode(url));
 */

Review
At reading the problem I thought it needed to be a lossless compression algorithm to generate a unique id.
The most basic compression is run length encoding on the bits that make the url. Or a dictionary compression on bit patterns such as Lempel, Ziv, Welch compression  AKA LZW or LZ compression. However there is some storage overhead and for short URLs you will have trouble getting a smaller url than the original.
Random id?
Your solution stores the original url mapped to a random index. There is no need for a compression or even a hash as all you need is a unique id per URL.
To generate an unique id you need only the number line. JS Number can generate 9e15 unique ids, that's a new id every millisecond for the next quarter million years (twice that if you include negatives).
You can also compress the id by converting the id to base 36 (the max base for Number.toString(radix)) thus the longest encoding is "2gosa7pa2gv" and the shortest is "0" and you need store only one 64bit double for the short url.
See Example
Bug?
Your function returns a different short url for the same long url.
Example

Simple index encoding, there is room for lots of optimization in storage.

Produces safe urls using only a-z0-9 to encode.

There is a limit as it does rely on the hashing function (Chance of a clash) of the JS engine.

Checks if a url has already been encoded

You can avoid the JS hash functions (and possible clash), by using an array or set of arrays (if number of urls high) but that comes with a huge CPU cost of locating the URL if the data set is big will require a linear search of the stored urls when encoding. Decoding will still be fast as the encoded url contains the index of the original url
const PREFIX = 'http://tinyurl.com/';
const urls = {
    short: new Map(),  // can be array use id to index
    long: new Map(),   // can be array and use find rather than has and get
    value: 0,
    get id() { return urls.value++ },
};
function encode(url) {
    if (urls.long.has(url)) { return PREFIX + urls.long.get(url).id.toString(36) }
    const urlEntry = { url, id: urls.id };
    urls.long.set(url, urlEntry);
    urls.short.set(urlEntry.id, urlEntry);
    return PREFIX + urlEntry.id.toString(36);
}
function decode(url) {
    return urls.short.get(parseInt(url.split(PREFIX)[1], 36)).url;
}


Why is append() slower than + and is there some oversight in the map() solution which slows it down? I was trying out some variation in implementation of a leetcode example and was surprised by the runtimes. I was expecting it would be better to use map() than classic grandpa style for-loop

In short the problem is to find if a value in the list is smaller or larger than a threshold value

https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/submissions/

Here are the three implementations:

72 ms 13.8 MB

Map over the input list and generate the list of bool

class Solution:
    def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:

        m=max(candies)-extraCandies
        return list(map( lambda x: x>=m, candies))

40 ms 14 MB

For-loop and append() to list

class Solution:
    def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:

        m=max(candies)-extraCandies
        ans=[]
        for x in candies:
            ans.append(x>=m)
        return ans

28 ms 13.6 MB

Use + to append to list

class Solution:
    def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:

        m=max(candies)-extraCandies
        ans=[]
        for x in candies:
            ans+=[(x>=m)]
        return ans

Why is append() slower than + and is there some oversight in the map() solution which slows it down?

You ask whether there is an oversight in the map solution, slowing it down.
There is, in the form of lambda.
When passing lambda objects, map is slowed down, as shown here.
Passing proper function objects does not have the same restrictions.

Other than that, I was unable to confirm the large performance discrepancy you found between append (40ms) and __iadd__/+= (28ms).
In the below tests, append is faster than += by (just) about 2 percent.
That is negligible.

Below, five versions of your function are tested.
Next to kidsWithCandies_map_builtin, which uses the ge function of the operator module to get a callable ge(a, b) that returns the same as a >= b, the arguably most Pythonic approach is also tested, list comprehension.

from collections import defaultdict, namedtuple
from operator import ge
from pprint import pprint as pp
from timeit import timeit
from typing import List

candy_distribution = namedtuple(
    "CandyDistribution", ["candies", "extra_candies", "solution"]
)

candy_distributions = [
    candy_distribution([2, 3, 5, 1, 3], 3, [True, True, True, False, True]),
    candy_distribution([4, 2, 1, 1, 2], 1, [True, False, False, False, False]),
    candy_distribution([12, 1, 12], 10, [True, False, True]),
]

def kidsWithCandies_map_lambda(candies: List[int], extraCandies: int) -> List[bool]:

    threshold = max(candies) - extraCandies
    return list(map(lambda x: x >= threshold, candies))

def kidsWithCandies_map_builtin(candies: List[int], extraCandies: int) -> List[bool]:

    threshold = max(candies) - extraCandies
    thresholds = [threshold] * len(candies)
    return list(map(ge, candies, thresholds))

def kidsWithCandies_append(candies: List[int], extraCandies: int) -> List[bool]:

    threshold = max(candies) - extraCandies
    ans = []
    for x in candies:
        ans.append(x >= threshold)
    return ans

def kidsWithCandies_iadd(candies: List[int], extraCandies: int) -> List[bool]:

    threshold = max(candies) - extraCandies
    ans = []
    for x in candies:
        ans += [(x >= threshold)]
    return ans

def kidsWithCandies_comprehension(candies: List[int], extraCandies: int) -> List[bool]:

    threshold = max(candies) - extraCandies
    return [element >= threshold for element in candies]

functions_to_runtimes = defaultdict(int)

for func in (
    kidsWithCandies_map_lambda,
    kidsWithCandies_map_builtin,
    kidsWithCandies_append,
    kidsWithCandies_iadd,
    kidsWithCandies_comprehension,
):
    for candy_supply in candy_distributions:
        args = (candy_supply.candies, candy_supply.extra_candies)
        assert candy_supply.solution == func(*args)
        functions_to_runtimes[func.__name__] += timeit("func(*args)", globals=globals())

functions_to_runtimes = {  # sort by value, ascending
    k: v for k, v in sorted(functions_to_runtimes.items(), key=lambda item: item[1])
}

pp(functions_to_runtimes)

with an output of

{'kidsWithCandies_append': 2.2671058810083196,
 'kidsWithCandies_comprehension': 2.3766544990066905,
 'kidsWithCandies_iadd': 2.3180257579660974,
 'kidsWithCandies_map_builtin': 2.9652103499975055,
 'kidsWithCandies_map_lambda': 3.658640267996816}

So while there is not much of a difference between append, comprehension and in-place addition (+=), map is much improved by not using a lambda.

The most non-grandpa style approach is the list comprehension. map was even originally supposed to be dropped from Python 3; as such (but this is speculation), one can suspect that all the performance love and care went towards (list) comprehensions, append and +=. Others have tried here, but map, as a built-in, seems hard to introspect.

I omitted space complexity considerations because these seem similar for all approaches.


Concurrently Iterable Poor Array List As I wrote on SO, I need an ArrayList-like structure allowing just the following operations

get(int index)
add(E element)
set(int index, E element)
iterator()

while supporting iterations concurrent with modifications. While I'm waiting for something better, I tried it myself. It was a bit harder than expected, so I used synchronization, which made it easy again. I'm linking to the full code and the test and showing here the relevant part (i.e., everything but the imports).

/**
 * A data structure implementing a tiny subset of List operations and allowing concurrent access.
 *
 * See https://stackoverflow.com/q/26424030/581205 for requirements.
 */
public class ConcurrentIterable<E> implements Iterable<E> {
    class MyIterator extends UnmodifiableIterator<E> {
        @Override public boolean hasNext() {
            return index < size();
        }

        @Override public E next() {
            try {
                return get(index++); // Safe as the array never shrinks.
            } catch (final IndexOutOfBoundsException e) {
                // This is hacky, but better than checking the size upfront, as the size may change.
                throw new NoSuchElementException();
            }
        }

        private int index;
    }

    /**
     * The returned iterator may or may not see the changes made after its creation.
     * The only guarantee in case of concurrent modifications is is that
     * it sees no garbage provided that the items are immutable.
     */
    @Override public Iterator<E> iterator() {
        return new MyIterator();
    }

    public synchronized int size() {
        return size;
    }

    @SuppressWarnings("unchecked")
    public synchronized E get(int index) {
        checkElementIndex(index, size);
        return (E) data[index];
    }

    public synchronized void add(E element) {
        if (data.length == size) grow();
        data[size++] = element;
    }

    public synchronized void set(int index, E element) {
        checkElementIndex(index, size);
        data[index] = element;
    }

    private void grow() {
        data = Arrays.copyOf(data, newSize(data.length));
    }

    private static int newSize(int oldSize) {
        int result = oldSize + (oldSize>>3) + 4; // Grow by about 1/8 only.
        if (result-MAX_ARRAY_SIZE > 0) result = MAX_ARRAY_SIZE; // Handle overflow.
        if (result<=oldSize) throw new OutOfMemoryError();
        return result;
    }

    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; // See ArrayList.

    private int size;
    private Object[] data = new Object[4];
}

I'm aware that it's incompatible with the Collection or List interfaces, but it's not meant to be general use class (though it may change). I need no additional constructors or other features.

Concerning spacing and single line conditional statements... yes, I know, I just don't care (my own conventions differ slightly).

I'll probably try to re-implement this without synchronization as a challenge.

General

private static int newSize(int oldSize) {
    int result = oldSize + (oldSize>>3) + 4; // Grow by about 1/8 only.
    if (result-MAX_ARRAY_SIZE > 0) result = MAX_ARRAY_SIZE; // Handle overflow.
    if (result<=oldSize) throw new OutOfMemoryError();
    return result;
}

Alright, leaving aside the 1-liners (OK, I said it... it sucks), there are other things here too:

YOU THROW OutOfMemoryError

Ouch.
Additionally, the method is only called from one place (grow()), and the call-site has only one line of code. Moving this logic in to the grow() call would be fine.
Other methods call checkElementIndex(), but that method is not included with your code.
You have the Object[] data variable. This is a horrible datatype to use because it introduces the need to do the explicit casts in the rest of the code, like:

return (E) data[index];

it is now relatively common in Java to require the class is given at the same time as the constructor. If you have the following code:
private E[] data;

public ConcurrentIterable(Class<E> clazz) {
    @SuppressWarnings("unchecked")
    data = (E[])Array.newInstance(clazz, 4);
}

Then, when you want to create your list, you create it with:
ConcurrentIterable<MyClass> myiterable = new ConcurrentIterable<>(MyClass.class);

from that point on, the inner-content of the class never needs to do an explicit cast from the data store.
Synchronization
Synchronizing on the instance itself is an anti-pattern, generally. In your class, you have synchronized methods: public synchronized void add(E element), etc.
What this means is that anyone who has an instance of your class, can mess with your synchronization and create deadlocks. Someone does the following:
public class MyClass {
    private final ConcurrentIterable<String> iterable = new ConcurrentIterable<>();

    ....

    public void doSomething() {
        synchronized(iterable) {
            Thread.sleep(100000);
        }
    }

Now, suddenly, your code hangs and does not complete.
When using synchronization it is almost always a bug to have a synchronization point on a public/leaked instance.
Apart from that issue, the synchronization looks complete, but excessively scoped. You lock the whole data structure. Your instance is 'serialized', no matter how many threads you have, only one thread can be doing anything at any one time.
There has to be a better way....
Alternate scheme
If it was me, I would consider a combination of the AtomicReferenceArray an AtomicInteger, and a ReentrantLock. The system would look something like:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.locks.ReentrantLock;

public class ConcurrentIterable<T> implements Iterable<T> {

    private static final int CONTAINER_SHIFT = 10; // 1024 per container.
    private static final int CONTAINER_SIZE = 1 << CONTAINER_SHIFT;
    private static final int CONTAINER_MASK = CONTAINER_SIZE - 1;

    private final AtomicInteger size = new AtomicInteger();
    private final ReentrantLock lock = new ReentrantLock();
    private final ArrayList<AtomicReferenceArray<T>> containers = new ArrayList<>();

    private final AtomicReferenceArray<T> getContainer(int index) {
        int cont = index >>> CONTAINER_SHIFT;
        lock.lock();
        try {
            while (cont >= containers.size()) {
                containers.add(new AtomicReferenceArray<T>(CONTAINER_SIZE));
            }
            return containers.get(cont);
        } finally {
            lock.unlock();
        }
    }

    private void checkIndex(final int index) {
        final int sz = size.get();
        if (index >= sz) {
            throw new NoSuchElementException(String.format("No element %d in structure of size %d", index, sz));
        }
    }

    public T get(final int index) {
        checkIndex(index);
        return getContainer(index).get(index & CONTAINER_MASK);
    }

    public T set(final int index, T value) {
        checkIndex(index);
        return getContainer(index).getAndSet(index & CONTAINER_MASK, value);
    }

    public void add(T value) {
        int index = size.getAndIncrement();
        getContainer(index).set(index & CONTAINER_MASK, value);
    }

    @Override
    public Iterator<T> iterator() {
        return new Iterator<T>() {

            int next = 0;
            final int last = size.get();

            @Override
            public boolean hasNext() {
                return next < last;
            }

            @Override
            public T next() {
                return get(next++);
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }

        };
    }

}

There is a race condition in the above, but I would probably solve it with documentation, not logic. The race condition is that there is a moment when you add a member, the size will be incremented, but the get() could return null in one thread in the instant before the value is set to the new value in another thread.
If you document that the container can hold null values, and that the iterator/get may return a null before the value is added, then you have the bonus of being able to support null values in the data too.
Note, it would be relatively trivial for the calling code to handle null return values.
There's a second caveat. I set up the iterator to loop to the last value that was added when the iterator was created. If you change the line:
return next < last;

to be
return next < size.get();

then you will iterate over all values added up to the last add. (but with slightly more risk that the last values may be null)


Flip Sprite using the SpriteRenderer component I want to create a 2D topdown game with Unity. When moving the player I also want him to rotate.

Most tutorials provide a solution changing the localscale of the transform component on the x axis setting -1 for left movement and 1 for right movement.

The attached SpriteRenderer component also got flipX and flipY checkboxes. I think setting these checkboxes by code might be more efficient.

Using this example code achieves the desired rotation

bool flipX;
bool flipY;

void Update()
{
    float horizontalInput = movementDirection.x;

    if (horizontalInput > 0)
    {
        flipX = false;
    }
    else if (horizontalInput < 0)
    {
        flipX = true;
    }

    float verticalInput = movementDirection.y;

    if (verticalInput > 0)
    {
        flipY = false;
    }
    else if (verticalInput < 0)
    {
        flipY = true;
    }

    spriteRenderer.flipX = flipX;
    spriteRenderer.flipY = flipY;
}

My question is: Is there a way avoiding these four if-statements? Maybe there is a more optimized way using some math.

If you need people to review your code you have to give a complete bunch of working code.
Here, we can only make assumptions about how what you show interoperate with what you don't show.

Your movementDirection..x and movementDirection..y can only be -1, 0, 1. Correct?
So, why using floats instead of ints ? Or even better, an enum, per example:

enum Movement
{
    Backward = -1,
    None = 0,
    Forward = 1
};

You only need flipping sprite if movements are negatives (for each axis). That's right?

Why just don't test for backwarding movement and set flipX to false otherwise (same for Y).

void Update()
{
    flipX = (movementDirection.x == Movement.Backward);
    flipY = (movementDirection.y == Movement.Backward);

    spriteRenderer.flipX = flipX;
    spriteRenderer.flipY = flipY;
}

Edit:
That's in case of neutral fixed states (Movement.None never flipped).
If when no movement you want to keep the last flipped states you still want two statement by axis.

void Update()
{
    if  (movementDirection.x != Movement.None)
        flipX = (movementDirection.x == Movement.Backward);
    if  (movementDirection.y != Movement.None)
        flipY = (movementDirection.y == Movement.Backward);

    spriteRenderer.flipX = flipX;
    spriteRenderer.flipY = flipY;
}

Edit 2:

For completeness, if you really want to minimize statements, you can use Convert, but i dont think it will improve performances :

void Update()
{
    if  (movementDirection.x != Movement.None)
        flipX = Convert.ToBoolean(movementDirection.x - 1);
    if  (movementDirection.y != Movement.None)
        flipY = Convert.ToBoolean(movementDirection.y - 1);

    spriteRenderer.flipX = flipX;
    spriteRenderer.flipY = flipY;
}


Simple class to access MySQL database I have written this simple DBHelper class to access a MySQL database. I am rethrowing a more generic exception so that the client side can take some action like showing a friendly message on the screen. Is it ok, or can something else be done?

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

using MySql.Data.MySqlClient;

namespace DBLibrary
{
    public class DBHelper
    {
        private MySqlConnection _connection;
        private string _server;
        private string _database;
        private string _uid;
        private string _password;

        private MySqlCommand _command;

        public DBHelper(string server, string database, string uid, string password)
        {
            _connection = new MySqlConnection();

            _server = server;
            _database = database;
            _uid = uid;
            _password = password;

            _connection.ConnectionString = String.Format("server={0};database={1};uid={2};password={3}", _server, _database, _uid, _password);
        }

        public MySqlParameterCollection Parameters
        {
            get { return _command.Parameters; }
            set
            {
                foreach (MySqlParameter param in value)
                    _command.Parameters.Add(param);
            }
        }

        public bool OpenConnection()
        {
            try
            {
                _connection.Open();
                _command = new MySqlCommand() { Connection = _connection };
            }
            catch (MySqlException ex)
            {
                //When handling errors, you can your application's response based on the error number.
                //The two most common error numbers when connecting are as follows:
                //0: Cannot connect to server.
                //1045: Invalid user name and/or password.
                switch (ex.Number)
                {
                    case 0:
                        throw new Exception("Cannot connect to server. Contact administrator !");

                    case 1045:
                        throw new Exception("Invalid username/password. Please check your connection string and try again !");
                }
                return false;
            }
            return true;
        }

        private bool CloseConnection()
        {
            try
            {
                _connection.Close();
                _refreshCommand(null);
                return true;
            }
            catch (MySqlException ex)
            {
                if (ex.InnerException == null)
                    throw new Exception(ex.Message);
                throw new Exception(ex.InnerException.Message);
            }
        }

        public int ExecuteStoredProcedure(string name)
        {
            _command.CommandType = System.Data.CommandType.StoredProcedure;
            _command.CommandText = name;
            int count = _command.ExecuteNonQuery();

            _refreshCommand(_connection);
            return count;
        }

        private void _refreshCommand(MySqlConnection con)
        {
            _command = new MySqlCommand() { Connection = con };
        }
    }
}

Property Parameters

The setter adds the new parameters to the list - I would expect, that the list will be cleared before.
The setter and getter throw a null reference exception if the connection was not opened before

Method OpenConnection

If an expected exception occurs, an exception is thrown; otherwise the method returns false. That is IMHO unusually... I would prefer to return a result like (enum OpenConnectionResult { ServerNotAvailable, AuthorizationFailed, UnknownError, Succeess }).
The error text of the exception can not be localized (that problem is also solved by the solution above)
If throwing a new exception, it makes sense to pass the underlying exception as inner exception to the new one (new Exception("Cannot connect to server. Contact administrator !", ex);)

Method CloseConnection

The methods returns always true or throws an exception.
The method is private and will not be called within the class.

if (ex.InnerException == null)
    throw new Exception(ex.Message);
throw new Exception(ex.InnerException.Message);

Don't do that... You hide valuable information that may be useful for error analysis! Just throw the exception here... You can handle that kind of stuff from outside if required.
What if the inner exception has another inner exception? If you want to get the most underlying exception use something like while(ex.InnerException != null) { ex = ex.InnerException; }

Method ExecuteStoredProcedure

The method throws a null reference exception if OpenConnection was not called.

Method _refreshCommand

Methods start with a capital letter in c# (even private ones)
Remember to dispose the command object!

General Design

Your class has some surprises for the user. The parameters can be set from outside, but after running a procedure, a new command is initialized and the modified parameter list is reset - very confusing! Even the error handling is not very usual.

I suppose, that you set the parameters before you are running ExecuteStoredProcedure!? If so, why not passing the command parameters to that method? There is no need for the class to know the command parameters.

IMHO that would simplify the usage of the class:

public class DBHelper
{
    private readonly MySqlConnection _connection;
    private readonly string _server;
    private readonly string _database;
    private readonly string _uid;
    private readonly string _password;

    public DBHelper(string server, string database, string uid, string password)
    {
        _server = server;
        _database = database;
        _uid = uid;
        _password = password;

        _connection = new MySqlConnection();
        _connection.ConnectionString = String.Format("server={0};database={1};uid={2};password={3}", _server, _database, _uid, _password);
    }

    public OpenConnectionResult OpenConnection()
    {
        try
        {
            _connection.Open();
        }
        catch (MySqlException ex)
        {
            switch (ex.Number)
            {
                case 0: return OpenConnectionResult.ServerNotAvailable;
                case 1045: return OpenConnectionResult.AuthorizationFailed;
                default: return OpenConnectionResult.UnknownError;
            }
        }
        catch (Exception ex)
        {
            return OpenConnectionResult.UnknownError;
        }
        return OpenConnectionResult.Succeess;
    }

    public void CloseConnection()
    {
        _connection.Close();
    }

    public int ExecuteStoredProcedure(string name, params MySqlParameter[] commandParamters)
    {
        using (var cmd = new new MySqlCommand())
        {
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Connection = _connection;
            cmd.CommandText = name;
            cmd.Parameters.AddRange(commandParamters);
            int count = cmd.ExecuteNonQuery();
        }
        return count;
    }
}


Middlewares with Route definition or Routes with Middleware definition I am currently working on an Node based Express application. I have found Express's middlewares approach quite pleasing however, we all run in scenarios where a certain route or routes don't need a specific middleware.

I have found two approaches:

Adding middleware globally exempting the routes it doesn't need to run for. express-jwt is good example of this:

app.use(jwt().unless(
    '/someroute',
    '/someotherroute',
    ...
);

app.use(someothermiddleware().unless(
    '/someroute2',
    ...
);

app.use(someothermiddlewaretoo().unless(
    '/someroute3'
    ...
);

Adding middleware(s) to each route you define:

route.get(
   '/someroute1',
   [ jwt(), someothermiddleware, someothermiddlewaretoo ],
   function(req, res) {
       ...
   }
);

route.get(
   '/someroute2',
   [ jwt(), someothermiddlewaretoo ],
   function(req, res) {
       ...
   }
);

route.get(
   '/someroute3',
   [ jwt(), someothermiddleware ],
   function(req, res) {
       ...
   }
);

I can see that Approach #2 looks like some work however, I believe Approach #2 is way better in terms of a large application where you might have nested routers. You can be on any route and know exactly what middlewares it gets executed with.

With Approach #1, you get things up and running easily but, it will be pain to check if this route is being included for specific middleware every time you try to fix a bug.

Which approach is better in your opinion? Or, is there another approach that you would like to share?

I personally prefer Approach 2 since it will increase readability and you can easily find out which middle-ware are applied to a route rather than to go to each excepted middle-ware and calculate. That is a lot of work for future purpose.


User input validation that might be unbreakable for C++ I am new to programming and have been having a lot of trouble with user input validation. Everything I found online I could break and I finally put this function together that appears to be unbreakable. It is for int and double specifically.

I am curious about how it might be critiqued by experienced programmers. How did I do? What can be improved? What are some issues I might run into? One issue I ran into was when I #include<Windows.h>, max() becomes an issue in this code, so I had to use #define NOMINMAX. I wonder if there is a way around that as well. I am using this code with Visual C++ in Visual Studio.

#include<iostream>
#include<string>
#include<limits>

using namespace std;

template<class T>
void input(T& input, int low, int high, string message)
{
input = low - 1;
while (input < low || input > high)
{
    cout << message;
    while ((cin >> input).fail() || cin.peek() != '\n')
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << message;
    }
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}

The #define NOMINMAX issue is easy to fix. To do so we need to remove(or move internally to our input function) the using namespace std; call as this pollutes our global namespace with max/min calls. See this for why it is bad practice to include the namespace.
Seeing as we only want to output our message string and do not care about copying, it is best to pass this to our function as const& std::string
I would change the function signature to make it easier to use in client code. Instead of passing in a temp var for input, just let the function return type T.
The type of low and high should be of the same type as T, not always int. For types such as double and float the comparisons may not always return expected results and may also need to be compared with some small epsilon value.
Finally we do not wish to modify low or high and should also pass them by const.

The final function might then look something like

#include<iostream>
#include<string>
#include<limits>

template<class T>
T ValidateInput(const T low, const T high, const std::string& message)
{
    using namespace std;

    T input = low - 1;

    while (input < low || input > high)
    {
        cout << message;
        while ((cin >> input).fail() || cin.peek() != '\n')
        {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cout << message;
        }
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }

    return input;
}


Bootstrap CSS Container Layout I've always been used to write my own CSS but I decided to give a go to twitter-bootstrap and I want to make sure I'm not using more HTML containers that I need to:

This is my code for a single element of a list:

     <input type="email" class="form-control" placeholder="Enter email" value="vitor.monteiro@ubs.com">

My main issue with this is to have two
 wrapping single elements, in the first case it's an <input> and then a . If this was normal HTML I would condemn the DOM code as being inefficient and cluttered as the
 would not be necessary.

Is this a proper usage of twitter-boostrap if I want to create a form group element where the left side is an input and the right side the - icon?

Just like many CSS frameworks, bootstrap is meant to reduce (or even eliminate) the need to write CSS. Instead, it offers predefined classes to be used with divs to give the page a shape.

I agree that it might seem that the code above has "divitis." As a matter of fact, not even with CSS3 is it always possible to create a certain layout or style using semantic HTML only. So since the divs exist exactly for that, and using a framework might reduce development time by scales, I don't see anything bad with the code above. It's completely semantic, correct as of bootstrap, and apart from bootstrap itself contains no redundancy.


Using chartJS in Angularjs to plot IOT data I am a Javascript and AngularJS beginner.

Below is the code inside my chartController. What this does is get IOT data from a back-end call and display it in my front-end with a chart. There are two helper functions for the  chart: addData() and remove() to add and remove data. These functions make it so that the chart gets new data to the right of the chart and removes data on the left. This is what I have so far.
It would be appreciated if someone would give me tips on how:

to make my controller less stacked, get data -> draw chart -> update chart.
to make the get method more generic. The URL is now hardcoded.

var vm = this;
vm.content = [];
vm.dataContent = [];

$http({
  method: 'GET',
  url: 'http://localhost:8080/data/Living Room'
})
  .then(function successCallback(response) {

    JSON.stringify(response.data);

    angular.forEach($scope.content, function (value) {
      vm.dataContent.push(value.inputData);

    });

    $scope.content = response.data;

    var canvas = document.getElementById("myChart");
    var ctx = canvas.getContext("2d");

    var dataChart = {
      labels: ["January", "February", "March", "April", "May", "June", "July"],
      datasets: [{
        label: "Testing my Set",
        data: vm.dataContent
      }]
    };;

    var settings = {
      type: "line",
      data: dataChart
    };

    var myNewChart = new Chart(ctx, settings);

    function addData(chart, data, label) {
      chart.data.labels.push(label);
      chart.data.datasets.forEach(function (dataset) {
        dataset.data.push(data);
      });
      chart.update();

    }

    function remove(chart) {
      chart.data.labels.shift();
      chart.data.datasets.forEach(function (dataset) {
        dataset.data.shift();
      });
      chart.update();
    }

    setInterval( function(){

      addData(myNewChart, 16,  'working on it');

      // Remove the first point so we dont just add values forever
      remove(myNewChart);
    }, 5000);

  }, function errorCallback(response) {
    return alert(response.status)
  });

Feedback

The code appears to make good use of AngularJS and ChartJS, as well as promises.

For the function that handles the response, I had to move the line that assigns response.data to $scope.content up before the call to angular.forEach(). Otherwise it seems that the data wouldn't get assigned before the iteration...

Also I don't see the point of calling JSON.stringify() on the response.data object unless that gets assigned to a variable or passed to another function...

function handleResponse(response) {
    //what is the point of this line? the return value isn't assigned to a variable or passed to a function
    JSON.stringify(response.data);
    $scope.content = response.data;
    angular.forEach($scope.content, function (value) {
        vm.dataContent.push(value.inputData);
    });
}

Recommendations

Below are my recommendations. They are by no means a definitive list of improvements but will hopefully be useful in terms of readability, flow of the code, etc. In general, I aim to avoid lengthy functions - with ~10-20 lines or fewer. For more guidance, refer to answers on this post.

Making separate functions

  to make my controller less stacked, get data -> draw chart -> update chart.

First, I would move the implementation of the successCallback() and errorCallback() functions out to be defined later. Hoisting can be utilized here so the functions can be defined after being called, though one could also move the definitions up if desired. And if there was a need to call the functions multiple times, then the functions could be referenced simply by name in each instance.

$http({
    method: 'GET',
    url: 'http://localhost:8080/data/Living Room'
})
    .then(successCallback, errorCallback);

function successCallback(response) {
    JSON.stringify(response.data);
    //skipping the rest of the implementation
}
function errorCallback(response) {
    return alert(response.status);
}

Then I would break out the blocks within successCallback into separate functions. Even if they aren't called in multiple places, it can improve readability. While there are varying opinions, many people argue methods should be kept between 5-15 lines (refer to this answer - I know that is tagged with java and c# but it can apply to many other languages as well).

In the example below, I made one function to handle taking the response, and a separate function to get the settings passed to the chart constructor.

function successCallback(response) {
    handleResponse(response);

    var canvas = document.getElementById("myChart");
    var ctx = canvas.getContext("2d");

    var myNewChart = new Chart(ctx, getSettings());
    setInterval( function(){
        addData(myNewChart, 16,  'working on it');
        // Remove the first point so we dont just add values forever
        remove(myNewChart);
    }, 5000);
};
function handleResponse() { ... }
function getSettings() { ... }

Making URL variable

  to make the get method more generic. The URL is now hardcoded.

There are various ways to make the URL a variable. One approach is to have it be controlled by user interaction. For example, the UI could have inputs bound to the url via ngBind. And another approach might be to have specific URLs defined in the controller and reference those URLs. So in the controller, we could define:

$scope.urls = {
    livingRoom: 'http://localhost:8080/data/Living Room,'
    hallway: 'http://localhost:8080/data/Hallway'
}; //add more elements as appropriate

Then in the UI, have buttons like:

<button ng-click="loadData(urls.livingRoom)">Living Room</button>
<button ng-click="loadData(urls.hallway)">Hallway</button>

And define that function loadData like below, moving the call to $http() into it:

$scope.loadData = function(url) {
    if (interval) { //check if interval is updating data periodically
        clearInterval(interval);
    }
    $http({
        method: 'GET',
        url: url //use variable value based on parameter from button
    }).then(successCallback, errorCallback);
};

You may notice that function begins by checking if (interval) and if that evaluates to true then it will call clearInterval() passing that value. That will handle clearing the previous interval, as long as we assign the return value from setInterval() to that value:

var interval; //set scope outside functions
function successCallback(response) {
    //...handle response
    //...create chart
    interval = setInterval(function() {...},5000);
}

Demonstration

See a demonstration here in this phpfiddle.

Conclusion

If you look at the functions in that phpFiddle example, then you will notice that the longest function (excluding the controller callback) is ~9 lines long. This greatly enhances readbility.

JS error on hover

I noticed that after loading data from one source, then reloading with another source, when hovering over the chart I would see an error in my console:

  Uncaught TypeError: Cannot read property 'skip' of undefined

That appears to be this reported ChartJS bug.


Hackerrank Modular Range Queries Given an array, A=[a0,a1,a2...an], perform queries in the form left
  right x y. For each query, print the number of elements satisfying
  the following criteria:

  left < i < right
  a[i] = y(mod x)

  Note: We can write a[i] = y(mod x) as a[i] % x == y in most popular
  programming      languages.

  Input Format

  The first line contains two space-separated integers describing the
  respective values of (the size of ) and (the number of queries). The
  second line has space-separated integers describing the respective
  values of . Each of the subsequent lines describes a query in the form
  left right x y.

  Output Format

  For each query, print an integer denoting the number of array elements
  satisfying the given criteria on a new line.

  Sample Input 0

5 3
250 501 5000 5 4
0 4 5 0
0 4 10 0
0 4 3 2

  Sample Output 0

3
2
2

Can this code be optimized in any way?

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int n,q;
    cin>>n>>q;
    int A[n];
    for(int i=0;i<n;i++)
        cin>>A[i];
    while(q--)
        {
       int a,b,x,y,c=0;
        cin>>a>>b>>x>>y;
        for(int i=a;i<=b;i++)
            {
            int t=A[i];
           if(t%x==y)
                c++;
        }
        cout<<c<<endl;
    }
    return 0;
}

Can this code be optimized in any way?

Some of the obvious points:

Remove unnecessary #include statements

Your code doesn't use any stuff from these headers

#include <cmath>
#include <cstdio>
#include <vector>
#include <algorithm>

So you can remove them.

Don't use using namespace std;

That's generally considered bad practice.

Rather use

using std::cout;
using std::cin;

if you want to avoid typing these out.

Use meaningful variable names

Variable names like

int n,q;
int A[n];

don't tell anything about their semantics.

Standard C++ doesn't support VLA's

Code like

int A[n];

isn't portable. Variable Length Arrays aren't supported by the current c++ standard.

Use

std::vector A(n);

instead to create a dynamically sized array.

Check for successful and valid input

cin>>a>>b>>x>>y;

You never check if the above statement succeeded before proceeding to apply the algorithm.

Better do something like

if(!(cin>>a>>b>>x>>y)) {
    std::cout << "Bad input encountered!" << std::endl;
    return 1;
}

Since

t%x

may segfault when x is zero, you should at east have an assert:

std::assert(x);
if(t%x==y) { // ...
}

Always use braces for scoped blocks

for(int i=0;i<n;i++)
    cin>>A[i];

should be

for(int i=0;i<n;i++) { // <<<<<<<
    cin>>A[i];
} // <<<<<<<<

Missing the braces makes that code error prone for changes. It's always better to  clarify the scope with conditional or loop statements.

Use prefix incrment (decrement) if you don't need to preserve the previous value

Instead of

for(int i=a;i<=b;i++)
c++;

use

for(int i=a;i<=b;++i)
++c;

You obviously don't need the old value preserved by the postfix increment operations.

Performance of formatted text extraction

  The values of of n,q,a,x,y,b are ranging from 1 to 40000. so it gets the timeout therefore it needs to further optimised

As for your performance concerns:

Formatted text extraction in c++ is costly. You may get a performance improvement just using scanf() in this case.

While

cin>>a>>b>>x>>y;

applies four function calls

scanf("%d %d %d %d",a,b,x,y);

would be only one call. Also the internal implementation of the formatted text extraction syntax boils down to some scanf() like functions for most of the c++ compilers anyways.


Optimizing simple prime number function test For my first basic project with functions, I wanted to make a program that would allow you to input a number, and it would output whether it was prime or not. For the most part, it's functional and working.

How can I optimize it to be more efficient? How can I make my code more readable for the next person? What are some good programming techniques?

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <math.h>

using namespace std;
int PrimeTest(int x);

int main()
{
    int X = 0;
    cout << "Enter a number ";
    cin >> X;
    cout << "\n\n\n\t\t\t";
    if (PrimeTest(X) == 1)
    {
        cout << X << " is prime";
    }
    else
    {

        cout << X << " is NOT prime";
    }

    cout << "\n\n\n\t\t\t";
    return 0;
}

int PrimeTest(int x)
{
    int b = 2;
    while (b < x)
    {
        if (x % b == 0)
        {
            int Answer = 0;
            return Answer;
        }

        b++;
    }
    int Answer = 1;
    return Answer;
}

You have both <cmath> and <math.h>, but you only need the former.  The latter is a C library.
You can have main() at the bottom, allowing you to eliminate the function prototype.
Do not use single-character variable names (except for simple loop counters, which can be simple).  They are hard to understand for others, and may even leave you confused in the future, especially if you expand on the program quite a bit.

As such, X should be renamed to something like number.
PrimeTest() should return bool, not int.  Returning an int is more common in C, but is not done in C++ (it's only done in main(), but it is special).  You'll then return either true or false and compare them as such.  This will also eliminate the need for Answer.
The final output can be simplified to a single-line ternary (?:) statement:

std::cout << X << " is " << ((PrimeTest(X)) ? "prime" : "NOT prime");

This is essentially a shorter way of writing an if/else statement, but is best done with simple cases such as this one.  If you'll ever need to expand on these conditions, then it would be better to go back to using curly braces.


Using CSS grid to align content in a non responsive div My job is to supervise a junior developer, but I am mainly a javascript developer and my CSS skills are a bit basic. However, I spotted some things in his CSS code that seem unorthodox to me. He committed some CSS code similar to  the one I post here:

        John
        John is an elephant

            1000 kg
            10 years old

         ...

And the sass:

.label-item {
  margin: .8rem;
  display: grid;
  grid-template-columns: 4.4rem 1fr 1.8rem;
  grid-gap: 0 1rem;
  background-color: grey;
  align-items: center;
  width: 300px;
  height: 80px;
  position: relative;

  .label-image-container {
    width: 50px;
    height: 50px;
    display: inline-block;

    img {
      max-width: 50px;
      max-height: 50px;
      float: left;
      position: relative;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      height: auto;
    }
  }

  .label-info {
    display: grid;
    position: relative;
    grid-gap: .3rem;

    .label-name {
      font-size: 1.2rem;
      line-height: 1.5rem;
      height: 1.4rem;
    }
    .description, .size, .age {
      font-size: 1rem;
      display: inline-block;
      float: left;
    }

    .age {
      margin-left: .8rem;
      float: right;
    }
}
  .more-button {
    height: 100%;
    background-color: black;
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    grid-row-end: span 1;
  }
}

this is a codepen of this code:
https://codepen.io/anon/pen/QXadMP

My questions are:

a. Is grid positioning appropriate to alight and place elements inside a div that is not the main website container. I know that it works, but is this best practice?

b. Is nested grids considered to be best practice (.label-info inside .label item)?

c. Is using 'display: flex' appropriate to use just to align the content of a div in center?

I think the CSS looks fine. To your questions

a.) It doesn't matter which container has the grid property. It's CSS. It's not semantic.

b.) I am not sure if it is considered a best practice, but a lot of people seem to use it this way. Just google CSS nested grid and you will get quite some articles and videos on that topic. For example this and this.

c.) Counter question: Why not? CSS doesn't add any semantic meaning to HTML. It's just for styling. So, IMHO as long as it works and is scalable/maintainable it's fine.


Validate input that maps int to enum I've written the following enum and have added a function, fromValue that allows the caller to map given int into the enum value. I was wondering if the value passed to the function can be validated, or is returning a null in case the value isn't present in the map (is an invalid enum) sufficient?

public enum TestEnum {

    A(0x00),
    B(0x01),
    C(0x02);

    int test;

    private static final Map<Integer, TestEnum> VALUE_TO_TEST_ENUM;
    static {
        final Map<Integer, TestEnum> tmpMap = new HashMap<>();
        for (TestEnum testEnum : TestEnum.values()) {
            tmpMap.put(testEnum.test, testEnum);
        }
        VALUE_TO_TEST_ENUM = ImmutableMap.copyOf(tmpMap);
    }

    TestEnum(final int test) {
        this.test = test;
    }

    public static TestEnum fromValue(final int value) {
        // Add validation?
        return VALUE_TO_TEST_ENUM.get(value);
    }
}

Every instance in an enum already has an ordinal (the 0-based position of the value in the declaration order of the enum). For example, your instance C.ordinal() will return 2. See: Enum.ordinal(). These are the same values as the ones you are assigning to test. Is that a coincidence?

Additionally, you're using a small range of 0-based values for the test field, and as a consequence, an array will be a better storage option than a Map. Even if the array is as much as 80% empty it would still be more efficient (space and performance) than the Map.

About the exception - yes, I would throw a NoSuchElementException if the user tries to get a value that does not exist. Enums are compile-time constants and any use of the enum that's not legal should be reported, and found as soon as possible. In a sense, it's for this reason that Enums exist - to give compile-time certainty that your code references meaningful constants. The very fact that you are mapping the enum values back to an int is itself a bit concerning.

There is no need to make the Map a read-only map. The map is completely contained/encapsulated in the enum and no other write accesses exist, and no user can write to it, so it's redundant to make it read-only.

If your values can span a (very) wide range I would keep your Map-based lookup, but change the code to be:

private static final Map<Integer, TestEnum> VALUE_TO_TEST_ENUM = new HashMap<>();
static {
    for (TestEnum testEnum : TestEnum.values()) {
        tmpMap.put(testEnum.test, testEnum);
    }
}

public static TestEnum fromValue(final int value) {
    // Add validation?
    TestEnum v = VALUE_TO_TEST_ENUM.get(value);
    if (v == null) {
         throw new NoSuchElementException("No enum with value '" + value + "'.");
    }
    return v;
}

If your values are in a small range, at, or close to 0, I would do:

private static final TestEnum[] VALUE_TO_TEST_ENUM;
static {
    int max = 0;
    for (TestEnum testEnum : TestEnum.values()) {
        max = Math.max(max, testEnum.test);
    }
    VALUE_TO_TEST_ENUM = new int[max + 1];
    for (TestEnum testEnum : TestEnum.values()) {
        VALUE_TO_TEST_ENUM[testEnum.test] = testEnum;
    }
}

public static TestEnum fromValue(final int value) {
    // Add validation?
    if (value < 0 || value >= VALUE_TO_TEST_ENUM.length) {
         throw new NoSuchElementException("No enum with value '" + value + "'.");
    }

    TestEnum v = VALUE_TO_TEST_ENUM[value];
    if (v == null) {
         throw new NoSuchElementException("No enum with value '" + value + "'.");
    }
    return v;
}

If your test values are from 0 to n-1 and are the same as the ordinals of the enums, then I would completely get rid of the test value, and have the code:

private static final TestEnum[] VALUE_TO_TEST_ENUM;
static {
    VALUE_TO_TEST_ENUM = TestEnum.values();
}

public static TestEnum fromValue(final int value) {
    // Add validation?
    if (value < 0 || value >= VALUE_TO_TEST_ENUM.length) {
         throw new NoSuchElementException("No enum with value '" + value + "'.");
    }

    return VALUE_TO_TEST_ENUM[value];
}


Refactoring from .. in .. select to more compact one Is it possible to write the two following lines of code in a more compact one?

IEnumerable<int> collection = from partnerNumbers in contract.Contact.PartnerNumbers select partnerNumbers.Pnr;
var response = this.otherClass.SomeMethod(collection, DateTime.Now.Date);

Additional information:

public int SomeMethod(IEnumerable<int> partnerNumbers, DateTime startDate)
{
    ...
}

...

[Table("Conracts")]
public class Contract
{
    public virtual Contact contact
    {
        get;
        set;
    }
}

...

public class Contact
{
    public virtual Collection<PartnerNumbers> PartnerNumbers
    {
        get;
        private set;
    }
}

...

public class PartnerNumbers
{
    public int Id { get; set; }
    public virtual int Pnr { get; set; }
    public string Information { get; set; }
    public virtual Contact contact { get; set; }
}

Idon't see why you would want to shorten that piece of code but here's the same result in one line and using a LinQ method-chain instead of query-syntax:

var response = otherClass.SomeMethod(contract.Contact.PartnerNumbers.Select(p => p.Pnr), DateTime.Now.Date);

Edit:

Since you have no parameters that have influence on the calculation of the response, here's a method for re-usability:

public int GetResponse()
{
    var collection = from partnerNumbers in contract.Contact.PartnerNumbers select partnerNumbers.Pnr;
    var response = this.otherClass.SomeMethod(collection, DateTime.Now.Date);
    return response;
}

or with LinQ method-chain:

public int GetResponse()
{
    return otherClass.SomeMethod(contract.Contact.PartnerNumbers.Select(p => p.Pnr), DateTime.Now.Date);
}


Ruby implementation of Soundex algorithm I'm new to Ruby. I normally sling code in C#. What could I do to make this simple Soundex class more Rubyesque?

class Surname
  attr_accessor :value

  def initialize(input)
    @value = input
  end

  def soundex
    result = ''
    @value.chars.drop(1).each do |s|
      number = soundex_value(s).to_s
      result &lt;&lt; number unless result[-1,1] == number
    end
    @value.chars.first &lt;&lt; result.ljust(3,'0')
  end

  def soundex_value(s)
    case s
    when /[bfpv]/
      1
    when /[cgjkqsxz]/
      2
    when /[dt]/
      3
    when /l/
      4
    when /[mn]/
      5
    when /r/
      6
    else ''
    end
  end
end

def print_name(input)
  surname = Surname.new(input)
  puts(surname.value + ' => ' + surname.soundex)
end

['Smith', 'Johnson', 'Williams', 'Jones', 'Brown'].each do |s|
  print_name s
end

The output is:

Smith => S530
Johnson => J525
Williams => W452
Jones => J520
Brown => B650

Per your request, your code converted to the Ruby way perhaps would be as follows.

A small point: in our output, in the Ruby world, we would avoid the => fat comma which Rubyists (at least in the English-speaking world) call a 'hash-rocket' because:

It reads like Ruby's (older) hash accessing syntax.
In Ruby language documentation (e.g., see Array), the similar #=>, comprising a hash to introduce a comment, followed by a hash-rocket (presumably, this gave us the name), shows us the result (or value) of an individual line of code—the two meanings conflict.

BTW, we also would avoid ->, dash-greater-than, which in Ruby (syntax) generates a lambda.

class Soundex < String
  IGNORED_BEGINNING_LENGTH = 1
  MINIMUM_LENGTH = 3

  CASES = [ # Keep order.
    /[bfpv]/,
    /[cgjkqsxz]/,
    /[dt]/,
    /l/,
    /[mn]/,
    /r/,
  ]
  CASES_LENGTH = CASES.length

  def initialize(surname)
    a = surname.split ''
    kept    = a.take(IGNORED_BEGINNING_LENGTH).join ''
    indices = a.drop(IGNORED_BEGINNING_LENGTH).map do |e|
      (0...CASES_LENGTH).detect{|i| e =~ (CASES.at i)}
    end.compact
# Adjust to one-based notation; collapse repetition; right-pad with zeros.
    digits = indices.map(&:succ).join('').squeeze.ljust MINIMUM_LENGTH, '0'
    super kept + digits
  end

  def self.show(s) "#{s}: #{new s}" end
end

names = %w[Smith Johnson Williams Jones Brown Atchison]
names.each{|s| puts Soundex.show s}

gives the results

Smith: S530
Johnson: J525
Williams: W452
Jones: J520
Brown: B650
Atchison: A325


Structuring code logic for events on laravel controller The code below will store a base64 image on another website and create an event to display the image on a Vue page in real time. It works fine and all.
My question is, is this a good way of doing it or there's a better way to structure the code? I've thought about placing the logic in a listener but it doesn't seem that I need to use one. For queues, I'll add them later on.
Controller
public function store(Request $request)
{
    $base64 = $request->image;
    $image = str_replace('data:image/png;base64,', '', $base64);
    $imageName = 'draw'.time().'.png';
    $response = $this->guzzleClient()->post(config('archiving.api_postBase64_file'),
        [
            'multipart' => [
                [
                    'name' => 'file',
                    'contents' => $image
                ],
                [
                    'name' => 'file_name',
                    'contents' => $imageName
                ],
                [
                    'name' => 'file_folder',
                    'contents' => 'drawings'
                ],
            ],
        ]
    );
    if($response->getStatusCode() >= 500){
        return response($response->getBody(), $response->getStatusCode());
    }else{
        $drawing = Drawing::create([
            'user_id'=>Auth::id(),
            'file_name'=>$imageName,
        ]);
        event(new NewDrawing($drawing));
        return response('Drawing created!',200);
    }
}

NewDrawing Event
class NewDrawing implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $drawing;

    public function __construct(Drawing $drawing)
    {
        $this->drawing = $drawing;
    }
    public function broadcastOn()
    {
        return new Channel('channel-drawing');
    }
 }

Frontend (Vue)
<script>
export default {
    data(){
        return{
            images:'',
        }
    },
    methods:{
        listen() {
            Echo.channel('channel-drawing')
            .listen('NewDrawing', res => {
                this.images.push(res.drawing);
            })
        }
    },
    mounted() {
        this.listen()
    }
}
</script>

I'm mostly a back-end guy who fusses his way through front end code. Here's my advice:

Keep the controller code as close as possible to handling the response only. Delegate the creation of objects to their own classes. Think of the S in SOLID - Single Responsibility.
public function store(Request $request)
{
    $image = new ImageMeta($base64);
    $archiver = new ImageArchiver($image);
    $response = $archiver->post();

    if($response->getStatusCode() >= 500){
        return response($response->getBody(), $response->getStatusCode());
    }else{
        $drawing = Drawing::create([
            'user_id'=>Auth::id(),
            'file_name'=>$imageName,
        ]);
        //There's a few different ways to look at this which might be part of a larger conversation,
        // so I won't touch this part yet. But is this something specific to drawings? Or is the broadcast
        // of model creation something that will happen for lots of different models? Regardless, I would
        // change the name from NewDrawing to something like DrawingCreationBroadcast, or something like that
        // NewDrawing gets confusing since its too close to new Drawing();
        event(new NewDrawing($drawing));
        return response('Drawing created!',200);
    }
 }

ImageMeta class
    /** For all classes assume property declarations, and getters are included.
    * Lean toward immutable classes where possible, so don't include setters
    * unless it becomes necessary. Code re-use != object instance re-use.
    **/

    class ImageMeta {
        public function __construct($base64) {
            $this->image = str_replace('data:image/png;base64,', '', $base64);
            $this->imageName = 'draw'.time().'.png';
        }
    }

ImageArchiver class
    class ImageArchiver {
        private $config;

        public function __construct(ImageMeta $image) {
            $this->image = $image;
            $this->makeConfig();
        }

        private function makeConfig() {
            $this->config = [
                'multipart' => [
                    [
                        'name' => 'file',
                        'contents' => $image->getImage()
                    ],
                    [
                        'name' => 'file_name',
                        'contents' => $imageName->getName()
                    ],
                    [
                        'name' => 'file_folder',
                        'contents' => 'drawings'
                    ],
                ],
            ]
        }

        //use type hinting here. Off the top of my head I don't know the parent class of guzzleClient
        public function archive($guzzleClient) {
            return $guzzleClient->post($this->config);
        }

    }


Reverse the words, move the vowels and downcase everything I'm brand new to Ruby.
The function takes in a string of any number of words, and reverses the order of the words. Also, for each word, it takes the vowels and moves it to the end of the word. It also downcases everything. Thus, Hello World! would become wrld!o hlleo.
I am trying to use some Ruby features, hence why it is a one-liner so to speak. Basically I am just looking for style suggestions. Is it appropriate to do such a thing in this manner (one line?). I'm sure there are functions that could accomplish the task quicker, so I am open to those suggestions too, since my code is very long and convoluted. Also I should mention I wanted to write this with only base Ruby, no extra packages/gems.
Someone suggested Rubocop and the Style Guide so I will check those out.
  def funky_words(s)
    s.strip.gsub(/\s+/, " ").split(" ").reverse.instance_eval{map{|elt| elt.gsub(/([aeiou])/i,"")}}.
    zip(s.strip.split(" ").reverse.map{|elt| elt.scan(/([aeiou])/i).flatten}.instance_eval{map{|elt| elt.join}}).
    map(&:join).join(" ").downcase
    #first "line" reverses word order removes vowels, second "line" captures vowels, last "line" joins vowels and all words
  end

One-liners are good fun, but the world doesn't really need more of them. That said, they don't have to be so unreadable. What will your future brain say a year from now if you have to maintain that function?
Here's an approach illustrating a scalable technique to make even long "one-liners" readable by (1) using lines generously, (2) indenting code in the manner of a pretty-printed data structure to convey the logic's hierarchy (code is data, after all), and (3) including comments to assist the reader with the logic and intent.
def funky_words(s)
  (
    # Split into words.
    s
    .split
    .reverse_each
    .map { |word|
      # Within each word, push vowels to the end, while preserving
      # original order within consonants and vowels.
      word
      .each_char
      .sort_by.with_index { |c, i| "aeiouAEIOU".include?(c) ? [1, i] : [0, i] }
      .join
    }
    # Rejoin the new words.
    .join(" ")
  )
end


Percentage calculation What would be the best way to refactor following methods?

private string CalcualtePercentageDifference(string temp1, string temp2)
    {

        double number1 = ParseDouble(temp1);
        double number2 = ParseDouble(temp2);
        double percentageDifference = 0;

         if (number1 == 0 || number2 == 0)
         {
             return "0 %";
         }

        if ((number1 >= number2) && number1 > 0 && number2 > 0)
        {
            double tempNumber = number2*100/number1;
            Math.Abs(percentageDifference = 100 - tempNumber);
        }
        if ((number2 >= number1) && number1 > 0 && number2 > 0)
        {
            double tempNumber = number1*100/number2;
            Math.Abs(percentageDifference = 100 - tempNumber);
        }
        if (number1 < 0 && number2 > 0)
        {
            double tempNumber = (number2 + Math.Abs(number1))/Math.Abs(number1);
            Math.Abs(percentageDifference = 100 - tempNumber);
        }

        if (number2 < 0 && number1 > 0)
        {
            double tempNumber = (number1 + Math.Abs(number2))/Math.Abs(number2);
            Math.Abs(percentageDifference = 100 - tempNumber);
        }
        if (number1 < 0 && number2 < 0)
        {
            number1 = Math.Abs(number1);
            number2 = Math.Abs(number2);

            if ((number1 >= number2))
            {
                double tempNumber = number2 * 100 / number1;
                Math.Abs(percentageDifference = 100 - tempNumber);
            }
            if ((number2 >= number1))
            {
                double tempNumber = number1 * 100 / number2;
                Math.Abs(percentageDifference = 100 - tempNumber);
            }
        }

        return Math.Round(percentageDifference) + " %";

    }

    private static double ParseDouble(object value, string valueName = "")
    {
        double outValue = double.NaN;

        try
        {
            outValue = Convert.ToDouble(value);
        }
        catch (FormatException e)
        {
            //We will get here when value contains NumberDecimalSeparator different from this in current culture
            //Convert now using suitable culture
            outValue = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator == ","
                       ? Convert.ToDouble(value, CultureInfo.InvariantCulture)
                       : Convert.ToDouble(value, new CultureInfo("pl-PL"));
        }
        catch (InvalidCastException)
        {
        }

        return outValue;
    }

Let the operators and the numbers have some space to breathe. Looking at

double tempNumber = number2*100/number1;

it is hard to see that the variable is called number2. So by adding some horizontal space will increase the readability like so

double tempNumber = number2 * 100 / number1;

The if condition here

if ((number2 >= number1) && number1 > 0 && number2 > 0)

can be simplified by removing the check for number2 > 0. If number2 is greater than or equal to number1 and  number1 is greater than 0 then for sure number2 is also greater than 0.

The same is true for

if ((number1 >= number2) && number1 > 0 && number2 > 0)

    if (number1 < 0 && number2 < 0)
    {
        number1 = Math.Abs(number1);
        number2 = Math.Abs(number2);

        if ((number1 >= number2))
        {
            double tempNumber = number2 * 100 / number1;
            Math.Abs(percentageDifference = 100 - tempNumber);
        }
        if ((number2 >= number1))
        {
            double tempNumber = number1 * 100 / number2;
            Math.Abs(percentageDifference = 100 - tempNumber);
        }
    }

In this construct you are calculating the percentageDifference two times if number1 and number2 are both < 0 and are the same. Using an else if would skip this.

If you would declare tempNumber, which by the way is named sub optimal,  instead of percentageDifference outside of the if's you could remove a lot of code duplication by calling Math.Abs(percentageDifference = 100 - tempNumber); at the end of thr method. In addition why do you use it like this and not like

percentageDifference = Math.Abs(100 - tempNumber);

which would be more readable.