texts: Searching a huge number of strings from Excel to a large number of Text files

texts:
I have written this code to get the input string from the spreadsheet and search the string across the text files and state whether or not it is found in the Excel sheet.

Scenario:

Excel (sheet1):

ColumnA

AAA

BBB

Drive C:

C: should be give in Column D5.

It has subfolders TEMP1, TEMP2, ...

Folder C:\TEMP1\

It has these text files:

X1.txt (has content AAA)
X2.txt (doesn't have any search data)

Folder C:\TEMP2\

It has these text files:

Y1.txt (has content BBB)
Y2.txt (doesn't have any search data)

Public K As Integer
Dim fs As Object
Dim fso As Object
Public fpth As String
Public str As String

Public Sub SearchInSQSDatabase_Click()

Dim ws1 As Worksheet
Set ws1 = Sheets(1)

Dim ws2 As Worksheet
Set ws2 = Sheets(2)

K = 2

Dim i As Integer
i = 1
ws2.Cells(1, 4).Value = "Search String"
ws2.Cells(1, 5).Value = "Files"
ws2.Cells(1, 6).Value = "Comments"

Do While Cells(i, 1).Value <> ""
     'ws2.Cells(i, 1).Value = Cells(i, 1).Value
     str = Cells(i, 1).Value
     ShowFolderList (ws1.Cells(5, 4).Value)
     i = i + 1
Loop

End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Get the List of Files and folders
''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub ShowFolderList(folderspec)
   On Error GoTo local_err

 Dim f, f1, fc, s, sFldr

 Dim ws2 As Worksheet
 Set ws2 = Sheets(2)

 Set fs = CreateObject("Scripting.FileSystemObject")
 Set f = fs.GetFolder(folderspec)
 Set fc = f.SubFolders

  For Each f1 In fc
     ' If Right(f1, 1) <> "\" Then ShowFolderList f1 & "\" Else ShowFolderList f1
     If Right(f1, 1) <> "\" Then ShowFolderList f1 Else ShowFolderList f1
  Next
Set fc = f.Files
For Each f1 In fc
    ' ws2.Cells(K, 4).Value = folderspec & "\" & f1.Name
    fpth = folderspec & "\" & f1.Name
    StringExistsInFile (f1.Name)

    'K = K + 1
Next
local_exit:
     Exit Sub
 local_err:
    MsgBox Err & " " & Err.Description
    Resume local_exit
    Resume
 End Sub

 ''''''''''''''''''''''''''''''''''''''''''''''''''''''
 'Check for the String
 ''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub StringExistsInFile(fname)
Dim theString, callString As String
Dim path As String
Dim StrFile As String
Dim file
Dim line As String
Dim flag As String

Set fso = CreateObject("Scripting.FileSystemObject")
Dim ws2 As Worksheet
Set ws2 = Sheets(2)

theString = str
path = fpth
StrFile = Dir(path)

Do While StrFile <> ""

'Find TheString in the file
'If found, debug.print and exit loop

Set file = fso.OpenTextFile(path)
Do While Not file.AtEndOfLine
    line = file.ReadLine
    If InStr(1, line, theString, vbTextCompare) > 0 Then
        ws2.Cells(K, 4).Value = str
        ws2.Cells(K, 5).Value = fname
        ws2.Cells(K, 6).Value = "Srting is found"
        flag = "Y"
    End If

Loop

file.Close
Set file = Nothing
Set fso = Nothing

StrFile = Dir()
Loop
If flag = "Y" Then
   K = K + 1
 Else
  ws2.Cells(K, 4).Value = str
  ws2.Cells(K, 5).Value = fname
  ws2.Cells(K, 6).Value = "String is not Found"
   K = K + 1
  End If

  End Sub

Output:

Output should be written in sheet2:

ColumnA columnB

AAA     X1

BBB     Y1

I have updated the code to have a hyperlink in the text file name to open the text file for the strings that are found, also need to no the count of column

added the below logic at the end, I feel the below code can be written in better way

Do While ws2.Cells(K, 6).Value <> ""
    K = K + 1
 Loop

Do While j < K

If ws2.Cells(j, 7).Value <> "" Then

    ws2.Cells(j, 7).Hyperlinks.Add Anchor:=ws2.Cells(j, 7), Address:= _
    ws2.Cells(j, 7).Value, TextToDisplay:=ws2.Cells(j, 7).Value

    ' ws2.Cells(j, 7).Formula = "=HYPERLINK(" & ws2.Cells(j, 7) & ",    Address = " & ws2.Cells(j, 7).Value & ")"
    'ws2.Hyperlinks.Add Anchor:=j, _
    'Address:=ws2.Cells(j, 7).Value, TextToDisplay:=ws2.Cells(j, 7).Value

    End If
  j = j + 1
Loop


texts: Loading and Refreshing DataGrid in WinForms using C# .Net Framework

texts:
I am looking for some review on the code I am about to provide below.

I'd like to improve my coding in general and happy to hear any comments from the community.

The goal of this code is simply load dataGridView1 with some data from MySQL and Refresh it with a click of a button.

I have not yet tried using automatic refresh. But will look into it soon or later.

Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Configuration;

namespace Final_Version
{
    public partial class Form19 : Form
    {
        public Form19()
        {
            InitializeComponent();
        }

        private void Form19_Load(object sender, EventArgs e)
        {
            RefreshGridHistory();
        }

        string connString = ConfigurationManager.ConnectionStrings["Final_Version.Properties.Settings.technicalConnectionString"].ConnectionString;

        public void RefreshGridHistory()
        {
            // MySQL connection string
            using (var conn = new MySqlConnection(connString))
            {
                //Seelct query
                using (var mySqlDataAdapter = new MySqlDataAdapter("select r.date_requested, u.username, r.product_code, r.customer_code " +
                                                                   " from verify v join request r on v.request_id = r.id join users u on r.user_id = u.id join" +
                                                                    " users u2 on v.user_id = u2.id where v.status = 'Verified' or v.status = 'Rejected';", conn))
                {
                    using (var dataSet = new DataSet())
                    {
                        DataSet DS = new DataSet();
                        mySqlDataAdapter.Fill(DS);

                        //Assign headers to Data Grid View
                        dataGridView1.DataSource = DS.Tables[0];
                        dataGridView1.Columns[0].HeaderText = "Date Requested";
                        dataGridView1.Columns[1].HeaderText = "User Requested";
                        dataGridView1.Columns[2].HeaderText = "Product Code";
                        dataGridView1.Columns[3].HeaderText = "Customer Code";

                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            RefreshGridHistory();
        }
    }
}


texts: Create a distribution from .xlsx file using Java

texts:
I have an Excel file with 2 columns, names and numbers. I want to know for each name what is the probability for each number. I prefer to do it in Java so I would be able to combine it with the rest of my project.
Actually, I already did it, and it's works, but I think it's done in a primitive and inefficient way.
Can you please suggest a better solution?
I thought about java stream but didn't know how.
My code:
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class HospitalizationDistribution {

    public static void main(String[] args) {
        HashMap<String, ArrayList<Integer>> map = readData("procedure and hospitalization time.xlsx");
        HashMap<String, HashMap<Integer, Double>> allDisributions = makeDisribution(map);

        HashMap<Integer, Double> example = allDisributions.get("Partial mastectomy");
        System.out.println("Partial mastectomy:");
        for (Entry<Integer, Double> entry : example.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }

    private static HashMap<String, ArrayList<Integer>> readData(String src){
        HashMap<String, ArrayList<Integer>> map = new HashMap<String, ArrayList<Integer>>();

        try {
            File file = new File(src); // creating a new file instance
            FileInputStream fis = new FileInputStream(file); // obtaining bytes from the file
            //creating Workbook instance that refers to .xlsx file
            XSSFWorkbook wb = new XSSFWorkbook(fis);
            XSSFSheet sheet = wb.getSheetAt(0); // creating a Sheet object to retrieve object

            String procedure;
            int duration;
            for (Row row : sheet) { // iterating over excel file
                procedure = row.getCell(0).getStringCellValue();
                duration = (int)row.getCell(1).getNumericCellValue();

                if(map.get(procedure) == null)
                    map.put(procedure, new ArrayList<Integer>());

                map.get(procedure).add(duration);
            }

            wb.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    private static HashMap<String, HashMap<Integer, Double>> makeDisribution(HashMap<String, ArrayList<Integer>> map) {
        HashMap<String, HashMap<Integer, Double>> allDisributions = new HashMap<String, HashMap<Integer,Double>>();

        String procedure;
        HashMap<Integer, Double> singleDisribution;
        ArrayList<Integer> durations;
        double sp; // single outcome probability
        for (Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
            procedure = entry.getKey();
            durations = entry.getValue();

            singleDisribution = new HashMap<Integer, Double>();
            sp = 1.0/durations.size();

            Double p;
            for (Integer i : durations) { // summing identical outcomes probability
                p = singleDisribution.get(i);
                if(p == null)
                    p = 0.0;
                singleDisribution.put(i, p + sp);
            }
            allDisributions.put(procedure, singleDisribution);
        }
        return allDisributions;
    }

The output:
Partial mastectomy:
3: 0.02233676975945018
4: 0.036082474226804134
5: 0.02920962199312716
6: 0.02233676975945018
7: 0.013745704467353955
8: 0.02577319587628867
9: 0.020618556701030934
10: 0.02233676975945018
11: 0.017182130584192445
13: 0.005154639175257732
.
.
.


texts: Generating Cartesian product of strings in R

texts:
Sometimes I need to create character vectors like this one:

datanames <- c(
  "europe_co2_min",
  "europe_co2_max",
  "europe_temperature_min",
  "europe_temperature_max",
  "asia_co2_min",
  "asia_co2_max",
  "asia_temperature_min",
  "asia_temperature_max"
)

Notice that this is actually the Cartesian product of the character vectors joined together with a _:

c('europe', 'asia')
c('co2', 'temperature')
c('min', 'max')

I came up with this helper function:

combine <- function(..., prefix='', sep='_') {
  combine.inner <- function(lx, ...) {
    if (length(c(...)) > 0) {
      sapply(sapply(lx, function(x) paste(x, combine.inner(...), sep=sep)), c)
    } else {
      lx
    }
  }
  paste(prefix, combine.inner(...), sep='')
}

It handles arbitrary number of character vector parameters of arbitrary lengths. The prefix parameter is for convenience.  It's similar to having a single element vector as the first parameter, except the common separator sep will not be applied after it.

Is there an easier way that exists in R and I missed?
Is there anything smelly about this code?


texts:
I wrote an implementation of binary search in JavaScript earlier for kicks, but I noticed my version was significantly different than those found on Google. Here is an example of binary search I found on Google (copied here to combat link rot):

Array.prototype.binarySearch = function(find, comparator) {
    var low = 0, high = this.length - 1,
        i, comparison;

    while (low <= high) {
        i = Math.floor((low + high) / 2);
        comparison = comparator(this[i], find);
        if (comparison < 0) { low = i + 1; continue; };
        if (comparison > 0) { high = i - 1; continue; };
        return i;
    }
    return null;
};

Most of the other implementations on Google are quite similar. But in mine, I don't subtract one from the low/high and continue from there. Instead, I divide the array in half and continue dividing the appropriate side in half until I reach the proper value. Code:

function binary_search_iterative(arr, ele) {
    var beginning = 0, end = arr.length,
        target;
    while (true) {
        target = Math.floor((beginning + end) / 2);
        if ((target === end || target === beginning) && arr[target] !== ele) {
            return -1;
        }
        if (arr[target] > ele) {
            end = target;
        } else if (arr[target] < ele) {
            beginning = target;
        } else {
            return target;
        }
    }
}

I wrote this recursive-style as well, but in testing I found this iterative version was faster.

In my tests, I've found that the examples I've found on Google (though they did not include the one above, they were nearly identical) are faster on smaller arrays, but as the input size increases, mine overtakes those. Since binary searches are usually limited (?) to larger input sizes, I see this as an improvement.

Is my thinking correct? Could this be done in an even better way?

I also do not like this:

if ((target === end || target === beginning) && arr[target] !== ele) {
    return -1;
}

And I was curious if there is a good way to eliminate it or refactor the function where it's cleaner in general.


texts:
I have a menu done in jQuery that I'd like some feedback on:

$(function() {
  // main expansion element
  $(".expander").click(function() {
    var subShown = $("ul > li", this).hasClass("show");
    if (!subShown) {
      $(".indented", this).slideDown('100').addClass("show");
      $(".caret", this).addClass("reversedCaret");
    } else {
      $(".indented", this).slideUp('100').removeClass("show");
      $(".caret", this).removeClass("reversedCaret");
      $(".indented--sub").slideUp('100').removeClass("show");
      $(".sub-caret").removeClass("reversedCaret");
      $(".more-or-less").text("More");
    }
  });

  // sub expansion element
  $(".sub-expander").click(function() {
    var subSelectText = $(".more-or-less").text();
    if (subSelectText != "More") {
      $(".indented--sub").slideUp('100').removeClass("show");
      $(".sub-caret").removeClass("reversedCaret");
      $(".more-or-less").text("More");
    } else {
      $(".indented--sub").slideDown('100').addClass("show");
      $(".sub-caret").addClass("reversedCaret");
      $(".more-or-less").text("Show Less");
    }
  });

  // stop propagation on the link element within .expander class
  $(".indented").click(function(event) {
    event.stopPropagation();
  });
});
.expander:hover {
  cursor: pointer;
}

.sub-expander--indented {
  padding: 0 0 0 23px;
}

.sub-caret {
  margin-right: 75px;
}

.indented,
.indented--sub {
  display: none;
}

.show {
  display: block;
}

  +

Item 1

Item 2

Item 3

Chapter 5

Chapter 6

Chapter 7

        +

More

This just seems like a really over the top way to do it, but the one thing I'm having a hard time with is differentiating the sub menu from the main expander without it's own class/ID.

Do you have any tips on how to improve this?


texts: This program asks users to rank an item and validates the rank

texts:
# get rank which takes the users rank as an argument and determines
# if it is valid input

def getRank(x):
    # make a list of the acceptable choices
    choices = ['l','m','h']
    # convert the users rank to lowercase
    x = x.lower()
    # create a while True loop that only runs if x is not in the choices
    while True:
        if x not in choices:
            # remind the user of the valid choices
            print('Only enter a valid choices')
            print(choices[0:3])
            x = input('Please enter a rank: ')
            x = x.lower()
            # add an if statement to continue the loop if the users new input is still incorrect
            if x not in choices:
                continue
        # if everything is all good break from the loop
        else:
            break
    return x

def main():
    print('Please enter a ranking for the items')
    print('l for low,m for medium,h for high')
    print('')
    print('Please enter a rank for milk')
    # prompt the user to enter their rate
    userRate = input('Please enter a rank: ')
    # validate their input
    validRank = getRank(userRate)
    # assign the users rating to validRank as it will only hold a valid choice
    # continue doing this for each item
    milkRate = validRank
    print('Please enter a rank for cheese')
    userRate = input('Please enter a rank: ')
    validRank = getRank(userRate)
    cheeseRank = validRank
    print('Please enter a rank for eggs')
    userRate = input('Please enter a rank: ')
    validRank = getRank(userRate)
    eggRank = validRank
    print('')
    #output the users ratings for the items
    print('Your overall ratings are:')
    print('Milk:',milkRate)
    print('Cheese:',cheeseRank)
    print('Eggs:',eggRank)

main()

Hi everyone! I'm a first year student and I would really love some tips to better my logic here. The above program does exactly what I want it to do: Display an item to the user, ask the user for their rank, validate that their rank is one of 3 choices case insensitive. If its invalid it requests reinput until it is. While this code works, I know there are oppurtunities for me to write better logic here.
I am open to all critiques here! Would just love feedback from the community


texts:
I am a beginner in Access SQL. I am in need of writing a parameter query for Access SQL and found a few tutorials and links for that but that wouldn't satisfy my requirement.

DB: Access DB

This updates a 'PD' column based on the values of 'OG', 'CPTY-BA' in an INPUT table. I need to calculate PD values from other reference tables 'PD', 'PD_MASTER_CPTY' and 'PD_MASTER_BG'.

Below is the VBA code with Access SQL with provided parameters. Is there any other way to write it in a single SELECT statement?

ElseIf (outputColumn = "PD") Then

strSQL = "SELECT [OG], CIF,[CPTY-BA], CIF_2 FROM INPUT   WHERE RUN_NUMBER='" + runNumber + "' ORDER BY CIF"
Set rs = CurrentDb.OpenRecordset(strSQL)

If Not (rs.EOF And rs.BOF) Then

     Do Until rs.EOF

        strOrigGroup = rs![Original Group]
        strCIF = rs![CIF]
        strCIF2 = rs![CIF_2]
        strBaselAsset = rs![CPTY-BA]

        If (strOrigGroup = "CB" Or strOrigGroup = "FID" Or strOrigGroup = "PB") Then

                strSQL1 = " SELECT DISTINCT  [INPUT].RUN_NUMBER, [INPUT].CIF, INPUT.CIF_2,[PD].[MID_PD] FROM [PD] INNER JOIN [INPUT] " + _
                          "ON [PD].CIF=[INPUT].CIF_2  WHERE [PD].[CIF]='" + strCIF2 + "' and [INPUT].RUN_NUMBER='" + runNumber + "'"
                Debug.Print strSQL1
                Set rs1 = CurrentDb.OpenRecordset(strSQL1)

                If Not (rs1.EOF And rs1.BOF) Then
                    strPD = CDbl(rs1![MID_PD])
                Else
                    strPD = "0.0229"
                End If

                strSQL = "update output set [PD] = '" + Format(strPD, "#.0000000000000") + "'  WHERE [OUTPUT].[CIF]='" + CStr(strCIF) + "' AND [OUTPUT].RUN_NUMBER='" + runNumber + "'"
                Debug.Print strSQL
                CurrentDb.Execute (strSQL)

        ElseIf (strBaselAsset = "BK" Or strBaselAsset = "BO" Or strBaselAsset = "SK") Then

                strSQL1 = "SELECT DISTINCT [INPUT].RUN_NUMBER,  [INPUT].CIF, [PD_MASTER_CPTY].[PD] FROM PD_MASTER_CPTY INNER JOIN INPUT ON [PD_MASTER_CPTY].COUNTERPARTY=INPUT.[CPTY-BA] WHERE [PD_MASTER_CPTY].[COUNTERPARTY]='" + strBaselAsset + "'AND [INPUT].CIF_2='" + CStr(strCIF2) + "' and [INPUT].RUN_NUMBER='" + runNumber + "'"
                Debug.Print strSQL1
                Set rs1 = CurrentDb.OpenRecordset(strSQL1)

                If Not (rs1.EOF And rs1.BOF) Then
                    strPD = CDbl(rs1![PD])
                Else
                    strPD = "0.0229"
                End If

                strSQL = "update output set [PD] = '" + Format(strPD, "#.0000000000000") + "'  WHERE [OUTPUT].[CIF]='" + CStr(strCIF) + "' AND [OUTPUT].RUN_NUMBER='" + runNumber + "'"
                Debug.Print strSQL
                CurrentDb.Execute (strSQL)

        Else
                strSQL1 = "SELECT [INPUT].RUN_NUMBER, [INPUT].CIF,[PD_MASTER_BG].[PD] FROM [PD_MASTER_BG] INNER JOIN INPUT ON [PD_MASTER_BG].[BUSINESS_GROUP]=INPUT.[ORIGINAL GROUP] WHERE [PD_MASTER_BG].[BUSINESS_GROUP]='" + strOrigGroup + "'AND [INPUT].CIF_2='" + CStr(strCIF2) + "' and [INPUT].RUN_NUMBER='" + runNumber + "'"
                Debug.Print strSQL1
                Set rs1 = CurrentDb.OpenRecordset(strSQL1)

                If Not (rs1.EOF And rs1.BOF) Then
                    strPD = CDbl(rs1![PD])
                Else
                    strPD = "0.0229"
                End If

                strSQL = "update output set [PD] = '" + Format(strPD, "#.0000000000000") + "'  WHERE [OUTPUT].[CIF]='" + CStr(strCIF) + "' AND [OUTPUT].RUN_NUMBER='" + runNumber + "'"
                Debug.Print strSQL
                CurrentDb.Execute (strSQL)

        End If

        rs.MoveNext
        Loop

End If


texts:
How can I refactor this code to avoid switch-cases? Is there a way of changing commands without adding new case and make it dynamically...I want the solution not to depend on the amount of cases. For example, if I have 1000 commands..I should obviously write them all as cases?
I hope my problem is clear.

static void Main(string[] args)
{
    ConsoleHelp ch1 = new ConsoleHelp();
    Plus pl = new Plus();
    Minus mn = new Minus();
    Divide dv = new Divide();
    Multiply mlt = new Multiply();
    Sinus sin = new Sinus();
    Tangent tan = new Tangent();
    Square sq = new Square();
    Degree dg = new Degree();
    Percent pr = new Percent();

    while (true)
    {
        Console.Write("command> ");
        string com = Console.ReadLine();
        if (com != null)
        {
            switch (com.ToLower())
            {
                case "?":
                    ch1.Helpper();
                    break;
                case "plus":
                    pl.Sum();
                    break;
                case "minus":
                    mn.Minusvalue();
                    break;
                case "divide":
                    dv.Dividevalue();
                    break;
                case "multiply":
                    mlt.Multvalue();
                    break;
                case "sinus":
                    sin.Sinusvalue();
                    break;
                case "tangent":
                    tan.Tangentvalue();
                    break;
                case "square":
                    sq.Squarevalue();
                    break;
                case "degree":
                    dg.Degvalue();
                    break;
                case "percent":
                    pr.Pervalue();
                    break;
                case "c":
                    Environment.Exit(0);
                    break;

                default:
                    Console.WriteLine("The command is not supported. Enter one of the valid commands.");
                    break;
            }
        }
    }
    Console.ReadLine();
}


texts: Parallax animation running well on Chrome but slow on Safari

texts:
This is the continuation of a previous question I posted here.

I've improved (at least I think so) the initial script from the previous question, now storing the data in an array, it runs slightly better, but still sometimes there's some lag in safari. I've tried to call requestAnimationFrame on scroll and cancelAnimationFrame on scroll end, but the animation was a little jumpy so I removed that.

This is the updated code:

var animationId,
    parallaxElements = [];

// Push elements to array
s.parallaxElements.each(function (i) {
  var i = {
    element: $(this),
    ratio: $(this).data('parallax-ratio'),
    offset: $(this).closest('.parallax-section').offset().top - 60,
    current: 0
  };

  parallaxElements.push(i);
});

// Animation
function animation() {
  var scrollPos = s.theWindow.scrollTop();

  for (var i = 0; i < parallaxElements.length; i++) {
    var self = parallaxElements[i],
        current = self.current,
        position = current - (current - (self.offset - scrollPos) * self.ratio) * 0.1;

    if (position !== current) {
      self.element.css('transform', 'translateY(' + position + 'px)');
      self.current = position;
    }
  }

  animationId = window.requestAnimationFrame(animation);
}

window.requestAnimationFrame(animation);


texts: Coded a Go Script that Sends proxy requests to backend servers

texts:
I've started Go for the last couple of months and I decided to challenging small projects, so I created this proxy requests script.
It works well (in my opinion at least) but I'm looking for different ways of improving this further like being able to target all servers, or making this more concise and compact. To be honest I think it is readable but again that's my opinion. I'm looking for it to be peer reviewed with no holds barred critism of my code. Why? to learn new ways of improving my coding techniques and making it much more efficient.
If anyone wants to view the code feel free:
package main

import (
    "context"
    "fmt"
    "math/rand"
    "time"
)

type frame struct {
    context.Context
    resp chan<- string
}

type frames chan frame

func main() {
    var serverConns []frames
    const totalServers = 10
    for i := 0; i < 10; i++ {
        serverID := i
        conn := make(frames)
        defer close(conn)
        serverConns = append(serverConns, conn)
        go func() {
            // the server
            for frame := range conn {
                resps := []string{"banana", "apple", "guava"}
                time.Sleep(50*time.Millisecond + time.Duration(rand.Intn(500))*time.Millisecond)
                r := fmt.Sprint("server ", serverID, ": ", resps[rand.Intn(len(resps))])
                select {
                case <-frame.Done():
                case frame.resp <- r:
                }
            }
        }()
    }
    // the proxy
    const maxFanout = 3
    var conns []frames
    connIDs := rand.Perm(len(serverConns))[:totalServers/2]
    for _, connID := range connIDs {
        fmt.Println("selected server:", connID)
        conns = append(conns, serverConns[connID])
    }
    fanoutConn := make(frames)
    go func() {
        for p := range fanoutConn {
            ctx, cancel := context.WithCancel(p.Context)
            firstResp := make(chan string)
            for _, serverConn := range conns {
                serverConn := serverConn
                fwdframe := frame{
                    Context: ctx,
                    resp:    firstResp,
                }
                go func() {
                    serverConn <- fwdframe
                }()
            }
            response := <-firstResp
            cancel()
            p.resp <- response
        }
    }()
    // the client
    for {
        r := make(chan string)
        p := frame{
            Context: context.Background(),
            resp:    r,
        }
        fanoutConn <- p
        fmt.Println(<-r)
    }
}


texts: How many ways we can make the change of the amount using the coins given

texts:
Given a set of coins and amount, write an algorithm to find out how
  many ways we can make the change of the amount using the coins given.

  Example:

  Amount = 5

  coins [] = {1,2,3}

  Ways to make change = 5

  {1,1,1,1,1} {1,1,1,2}, {1,2,2}, {1,1,3} {2,3}

The code I've written works flawlessly, but the time complexity is too high. If you could suggest an improvement for this code or suggest a better approach, please let me know.

public class CoinChangeProblem {
    public static void main(String[] args) {

        calculatePossibleCombinations(0, 0);
        System.out.println("Answer : "+totalCombinations);

    }

    static int[] coins = { 1, 2, 3};
    static int amount = 5;

    static int totalCombinations= 0;

    static void calculatePossibleCombinations(int pos, int sum)
    {
        if(pos< coins.length)
        {
            int coin = coins[pos];
            for(int j=0; j<=amount/coin && sum<=amount; j++)
            {
                calculatePossibleCombinations(pos+1, sum);
                sum = sum + coin;
                if(sum == amount)
                {
                    totalCombinations++; break;
                }
            }
        }
    }
}


texts: An Express route, which renders a page, and makes use of socket.io

texts:
This is the code for a basic endpoint in my express app routes folder. This firstly renders a page, and then on a continuous loop, renders information about some random "Breaking Bad" character.

The idea is to have the page load, and then every two seconds, the page updates automatically with the new character info. Then two seconds later, a new character replaces the one on the screen, and so on.

To do this, I'm making use of a convenient Breaking Bad REST-ful API

const express = require("express");
const app = require("../app");
const router = express.Router();
const axios = require("axios");

const socket = require("../socketioAPI");

router.get("/", function(req, res, next) {
    runCharacterUpdateInterval();
    res.render("index", { title: "Breaking Bad Page" });
});

const runCharacterUpdateInterval = () => {
    const updateTime = 2000;
    setInterval(() => {
        updatePageWithRandomCharacter();
    }, updateTime);
};

const updatePageWithRandomCharacter = () => {
    createCharacter().then(profile => {
        socket.push("breaking bad", profile);
    });
};

const createCharacter = async () => {
    const characterId = getRandomCharacterId();
    const bio = await queryAPI("characters/" + characterId);
    const { quote } = await queryAPI("quote/random?author=" + encode(bio.name));
    const { deathCount } = await queryAPI("death-count?name=" + encode(bio.name));
    return await { bio, quote, deathCount };
};

const encode = name => {
    return name.replace(/ /g, "+");
};

const getRandomCharacterId = () => {
    const totalChar = 54;
    const initalChar = 1;
    return Math.floor(Math.random() * Math.floor(totalChar)) + initalChar;
};

const queryAPI = async endpoint => {
    const api = await axios.get(`https://www.breakingbadapi.com/api/${endpoint}`);
    if (await api.data[0]) return await api.data[0];
    else return { name: [], quote: [], deathCount: [] };
};

module.exports = router;

In the past, my code has been reviewed as "spaghetti-like", and not clean. I've been trying to fix this, and so any pointers on the style, readability, or anything code related would be greatly appreciated.


texts:
In short, what this script aims to do is take the following data:

1
Alpha
Beta
Delta
2
Beta
Echo
Foxtrot
Kilo
3
Alpha
Kilo
4
Beta
Echo
Kilo
Zulu

And re-arrange like this:

1       2        3      4
Alpha   Beta     Alpha  Beta
Beta    Echo     Kilo   Echo
Delta   Foxtrot         Kilo
        Kilo            Zulu

The code I have is as follows:

      Private Sub PrepareLibrary()

Application.ScreenUpdating = False

Dim Rng As Range
Dim i As Long
Dim n As Range
Dim x As Long
Dim Library As Worksheet
Dim LastRow As Long
Set Library = Sheets("Library")
i = 1
x = 0
LastRow = Library.Range("A1").SpecialCells(xlCellTypeLastCell).row

Do While i <= LastRow
Set Rng = Library.Range("A" & i)
Set n = Library.Range("A1")

If IsNumeric(Rng) = True Then
x = x + 1
Rng.Copy
n.Offset(0, x).Insert Shift:=xlDown
i = i + 1
ElseIf IsNumeric(Rng) = False Then
Rng.Copy
n.Offset(1, x).Insert Shift:=xlDown
i = i + 1
ElseIf Application.WorksheetFunction.CountA(Rng) = 0 Then
i = i + 1

End If
Loop
End Sub

Essentially, this runs through Column A one at time, copying each cell across individually, pasting into a new row whenever it comes across a number. It works well on small databases, but when expanding out to over 20,000 rows of data, I get a "not enough resources" message. Willing to attempt an entirely different approach if it seems possible. I'm new to VBA, so that may explain why this code is quite inefficient.


texts: Call multiple services from angular2 component

texts:
This is my first Angular2 component, which makes two api calls: the first call  provide the input for the the second one.

The following is my attempt at this code.

@Component({
      selector: 'result-panel',
      templateUrl: 'panel.component.html',
      styleUrls: ['panel.component.css'],
      providers:[FindIpZoneDataService,ApiService]
    })

    export class PanelComponent
    {
      networkDetail:Array<Network>;
      query = "";
      datafetchservice:any;
      searching:boolean = false;
      rowCount:boolean = false;
      iperror :boolean = false;
      nwerror :boolean = false;
      userinputerror:boolean = false;
      constructor(private dataservice :FindIpZoneDataService){
            this.datafetchservice = dataservice;
      }

      getNetworkDetail(ip:string) {
        this.networkDetail = [];
        this.dataservice.getNetworkDetail(ip)
          .map((response) => {
            let res: Array<any> = [];
            let extattrs: Array<any> = [];
            res = response.json();
            res.forEach((detail) => {
              extattrs.push(detail.extattrs);
            });
            return extattrs;
          })
          .map((network:Array<any>) => {
            console.log(network);
            let result: Array<Network> = [];
            if (network) {
              network.forEach((detail) => {
                result.push(new Network(detail['SITE Name'].value,
                  detail['InfoSec Security Zone'].value,
                  detail['Network Security Zone'].value,
                  detail['Data Classification'].value));
              });
              return result;
            }
          })
          .subscribe(details => {
              this.networkDetail = details;
              this.rowCount = true;
              this.searching = false;
            },
            err => {
              //Valid Network not found
              this.handleNwServiceError(err);
            });
    }
      getIPNetwork(){
        this.datafetchservice.getNetwork(this.query)
          .map(response => response.json())
          .subscribe(result => {
              this.getNetworkDetail(result[0].network);
          },
            err => {
              //InValid IP
              this.handleIpServiceError(err);
            });
      }

      private handleNwServiceError(error: any) {
        //Observable.throw(error.json().error || 'Invalid Network - Server error');
        console.log(error);
        this.nwerror = true;
        this.rowCount = false;
      }

      private handleIpServiceError(error: any) {
        //Observable.throw(error.json().error || 'Invalid IP - Server error');
        console.log(error);
        this.iperror = true;
        this.rowCount = false;
        console.log('ip error');
      }

Please let me know how I can improve it.


texts: Counter object in Python with public and private methods

texts:
I am trying to implement an open source desktop application with python. I want to provide both a gui and an API. I know there is no private methods in python but i am trying to find the most elegant way to keep some methods private. I do not want my users to see all list of methods while using API. After some research, I come up with the implementation below and wondering if there is any problem with my implementation of this concept and if there is any room for improvement. Please provide me a review and do not hesitate to ask any questions you have. Here is my try:

from pprint import pprint

# CamelCase because it "acts" like a class
def CounterController():
    class CounterControllerPrivate(object):
        def __init__(self):
            self.counter = 0

        def add_one(self):
            self.counter += 1

        def reset(self):
            self.counter = 0

        def get_counter(self):
            return self.counter

    counter_controller = CounterControllerPrivate()

    class CounterControllerPublic(object):
        def add_one_endpoint(self):
            counter_controller.add_one()
            return counter_controller.get_counter()

        def reset_endpoint(self):
            counter_controller.reset()
            return counter_controller.get_counter()

    return CounterControllerPublic()

# counter attribute is not accessible from out here
controller = CounterController()

print(controller.add_one_endpoint())
print(controller.add_one_endpoint())
print(controller.reset_endpoint())

pprint(dir(controller))


texts: Finding integer with the most natural dividers

texts:
Problem description: You are given a segment [568023; 569230]. Find integer within given range that has the most natural dividers. If 2 or more integers are found, return the lowest integer among them.
Solution:
def allnums(k):
    cnt = 0
    for i in range(2, k // 2):
        if k % i == 0:
            cnt += 1
    return cnt

MAX_NUM = 0
MAX = 0

for i in range(568023, 569231):
    cnt = allnums(i)
    if MAX < cnt:
        MAX = cnt
        MAX_NUM = i

print(MAX, ' ', MAX_NUM)

Output: 141   568260
Runtime: 17s

Question: Is there any way to make this code more concise, maybe also improving its runtime? Thank you in advance.


texts:
I am using a DataTable and the MySqlAdapater to insert around 100 000 rows with around 40 columns to a MySQL database.

I chose this way, because my program needs run on mono (unix / mac) where I could not establish a connection to my database via the System.Data.Sql package, but only via the .NET connector Mysql.Data.MySqlClient which has no SqlBulkCopy-method.

Additionally the amount of columns in my table is flexible, so I was looking for an easy way to iterate the columns. Thats why I used the way:

Parsing my data
Loading it into a DataTable Object
Create a MySQL table dynamically based on my DataTable Object
Use a MySqlDataAdapter to bulk insert the DataTable to the Database via its .Update()-method

Right now, it takes around 3-4 minutes to insert 100 000 rows this way - which is subjectively slow (mac mini 2012, i7, 512 GB SSD, 16 GB ram)

Is there any way to speed this up with the Mysql.Data.MySqlClient ?

public static void Import(DataTable dt, string tableName, string conString)
        {
            using (MySqlConnection con = new MySqlConnection(conString))
            {
                con.Open();

                string createTableString = GetCreateTableSql(dt, tableName);
                MySqlCommand cmd = new MySqlCommand(createTableString, con);
                cmd.ExecuteNonQuery();

                using (MySqlCommand selectcmd = new MySqlCommand("SELECT * FROM " + dt.TableName, con))
                {
                    using (MySqlDataAdapter sda = new MySqlDataAdapter())
                    {
                        MySqlCommandBuilder builder = new MySqlCommandBuilder(sda);
                        sda.SelectCommand = selectcmd;

                        builder.GetUpdateCommand();

                        using (DataTable dttemp = new DataTable())
                        {
                            sda.Fill(dttemp);
                            // prevent duplicating data
                            if (dttemp.Rows.Count == 0)
                            {
                                dttemp.Merge(dt);
                                sda.Update(dttemp);
                            }
                            else
                            {
                                Console.WriteLine("Data already present. Delete manually");
                            }

                        }
                    }
                }
            }
        }


texts: Count chars difference between two strings

texts:
Given two strings with the same length, we check how many chars on the same positions are different. For example: ABCD and ABBD should return 1. Here is a link to a gist with tests, to have a better understanding of what I'm building.
Here is my solution:

object Hamming {

  def compute(str1: String, str2: String):Int = {
    if (str1.length != str2.length)
      throw new IllegalArgumentException("Strings have different length")
    (0 to str1.length - 1).filter(i => str1(i) != str2(i)).size
  }

}


texts:
I have started a project in PHP with PDO and I'm almost done, but I've read somewhere that PDO escape alone is not secure and we have to consider some settings of PDP. I am a little confused about my PDO class and usage.

public function __construct(){
    //set DNS
    $dns = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname.';charset=utf8';
    //set options
    $options = array(PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",PDO::ATTR_EMULATE_PREPARES => false );
    //create a new PDO instance
    try{
        $this->dbh = new PDO($dns, $this->user, $this->pass, $options);
    } //catch any errors
    catch(PDOException $e){
        $this->error = $e->getMessage();
    }
}

public function query($query){
    $this->stmt = $this->dbh->prepare($query);
}

public function bind($param, $value, $type = null){
    if(is_null($type)){
        switch(true){
            case is_int($value):
                $type = PDO::PARAM_INT;
                break;
            case is_bool($value):
                $type = PDO::PARAM_BOOL;
                break;
            case is_null($value):
                $type = PDO::PARAM_NULL;
                break;
            default:
                $type = PDO::PARAM_STR;
        }
    }
    $this->stmt->bindValue($param, $value, $type);
}

public function execute(){
    return $this->stmt->execute();
}

public function resultset(){
    $this->execute();
    return $this->stmt->fetchAll(PDO::FETCH_OBJ);
}

public function single(){
    $this->execute();
    return $this->stmt->fetch(PDO::FETCH_OBJ);
}

public function rowCount(){
    return $this->stmt->rowCount();
}

Queries:

$db->query("SELECT * FROM XYZ WHERE some=:some");
$db->bind(':some', $$somevar);
$result= $db->resultset();   ///for select

$result= $db->single();  ///if we want single row

For inserting and updating:

$db->query("INSERT INTO XYZ (x,y,z) VALUES (:x,:y,:z)");
$db->bind(':x', $x);
$db->bind(':y', $y);
$db->bind(':z', $z);
$db->execute();

Is there anything wrong which will affect me in future? I have searched many things for PDO and have updated my class accordingly, but I want to be sure about my project.


texts: Check multiple subdirectories and delete if file exists

texts:
Long story short, I have over 180K files that I need to delete. I have all of the file names that need to be deleted in a TXT file, however the files that need deleting are scattered in over 400 folders within this one directory.

I'm attempting to design a script that reads a .TXT file, checks if the file exists in any of the sub directories and deletes if found.

I'm quite knew to PowerShell / Object-oriented scripts so need some assistance.

$WorkingDir = 'D:\TEST\'
$txtFile = Get-Content "D:\TEST\Files.txt"

#foreach file in the .TXT
foreach ($file in $txtFile){
    # foreach file in the folders
    foreach($dir in (Get-ChildItem $WorkingDir -Recurse)){
        # if the file name is in directory listed, then delete?
            If (Test-Path $file){
                Remove-Item $file
                  }
             }
      }

Example of data in TXT file:

215865.wav
215864.wav
215875.wav
215887.wav
215885.wav
215884.wav
215902.wav
215906.wav

Attempted to run script above on some test data so it didn't have to scan through hundreds of folders...runs successfully but nothing gets deleted.


texts:
Just started learning python and I'm solving some beginner problems. I wrote a solution for a question without any edge cases like user not entering anything, entering numbers etc.:

  Question: Write a program to print initial letter of an entered name?

  Expected output: If the user inputs,

  Ram Chandra Giri -> R.C.Giri
  Ram chandra Giri -> R.C.Giri

My solution works as expected but I would like insight on whether I am following best practice or not and if there is better and easier way to do it. Question is from Class 10 book for students to learn Q-BASIC.

My solution:

def initial_of_name(c):
    word_list = c.split(" ")
    i = (len(word_list) - 1)
    new_list = []
    for w in range(0, i):  # this loop leaves last name and creates a new list.
        word = word_list[w]
        word = word[0:1].upper()  # sliced word into initial letter
        new_list.append(word)
    new_list.append(word_list[-1])  # added last name to the list before joining.
    initial = '.'.join(new_list)
    print("The initial of your name is {0}.".format(initial))
    return

name = input("Please enter your name?\n>")
initial_of_name(name)


texts: Using decorator pattern to validate an entity

texts:
I am following this article.

/**
 * The group name should contain a minimum of 3 and a maximum of 12 capital letters.
 * No space, number, or special characters are allowed
 */

console.clear();

class Group {
  constructor(name) {
    this.name = name;
  }

  getName() {
    return this.name;
  }

  getLength() {
    return this.name.length;
  }

  add(name) {}

  remove(name) {}

  toString() {
    return `Group: ${this.name}`;
  }
}

class DefaultGroup {
  constructor(group) {
    this.origin = group;
  }

  getName() {
    return this.origin.getName();
  }

  getLength() {
    return this.origin.getLength();
  }

  validate() {
    return true;
  }
}

class OnlyUpCaseGroup extends DefaultGroup {
  constructor(origin) {
    super(origin);

    if (!this.validate()) {
      alert('Invalid group name ' + this.getName());
      throw Error('Invalid group name');
    }
  }

  validate() {
    let REGEX_UP_CASE = /^[A-Z]*$/g;
    return super.validate() && REGEX_UP_CASE.test(this.getName());
  }

  toString() {
    return `Group: ${this.getName()}`;
  }
}

class ValidLengthGroup extends DefaultGroup {
  constructor(origin) {
    super(origin);

    if (!this.validate()) {
      alert('Length must be between 3 and 12');
      throw Error('Invalid group name');
    }
  }

  validate() {
    let len = this.getLength();
    return super.validate() && len >= 3 && len <= 12;
  }

  toString() {
    return `Group: ${this.getName()}`;
  }
}

let g = new Group('FOOOBAAAR');
//console.log(new OnlyUpCaseGroup(new Group('vivek')));
//console.log(new OnlyUpCaseGroup(new DefaultGroup(g)));
//console.log(new ValidLengthGroup(new DefaultGroup(g)));
console.log(new ValidLengthGroup(new OnlyUpCaseGroup(new DefaultGroup(g))));

Questions:

I need to know if I am following the pattern properly?
Can I do same with less verbose code?

Note:

Maintainability and flexibility is prime here. Keep in mind that there can be more validations.


texts:
As a C++ beginner learning C++ and DirectX at the same time, I was wondering if a more experienced C++ developer would be able to go over the code and tell me what is done incorrectly or something that you would change.

Window.h

#pragma once

#include <string>
#include <windows.h>

namespace Graphics {

class Window
{
private:
    const char *m_Title;
    int m_Width;
    int m_Height;
    HINSTANCE m_hInstance;
public:
    Window(const char *title, int width, int height);
    ~Window();

    bool Init();
    bool CreateD3DWindow();
    void Loop();

    inline int GetWidth() { return m_Width; }
    inline int GetHeight() { return m_Height; }
};
}

Window.cpp

#include "Window.h"

#include <iostream>

namespace Graphics {

// Forward declarations
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

Window::Window(const char *title, int width, int height)
    : m_Title(title), m_Width(width), m_Height(height)
{
}

Window::~Window()
{

}

bool Window::Init()
{
    if (!CreateD3DWindow())
    {
        return false;
    }

    return true;
}

void Window::Loop()
{
    MSG msg;
    ZeroMemory(&msg, sizeof(MSG));

    while (msg.message != WM_QUIT)
    {
        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        else
        {
            // Render
        }
    }
}

bool Window::CreateD3DWindow()
{
    HWND hWnd;
    WNDCLASSEX wc;

    m_hInstance = GetModuleHandle(NULL);

    // Window styling and options
    wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    wc.lpfnWndProc = WndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = m_hInstance;
    wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
    wc.hIconSm = wc.hIcon;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = m_Title;
    wc.cbSize = sizeof(WNDCLASSEX);

    if (!RegisterClassEx(&wc))
    {
        std::cout << "RegisterClassEx failed!" << std::endl;
        return false;
    }

    hWnd = CreateWindowEx(
        WS_EX_APPWINDOW,
        m_Title,
        m_Title,
        WS_OVERLAPPEDWINDOW,
        GetSystemMetrics(SM_CXSCREEN) / 2 - m_Width / 2,
        GetSystemMetrics(SM_CYSCREEN) / 2 - m_Height / 2,
        m_Width,
        m_Height,
        NULL,
        NULL,
        m_hInstance,
        NULL
    );

    if (!hWnd)
    {
        std::cout << "Failed to create window" << std::endl;
        PostQuitMessage(0);

        return false;
    }

    ShowWindow(hWnd, SW_SHOW);

    return true;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_CLOSE:
        PostQuitMessage(0);
        return 0;

    case WM_KEYDOWN:
    {
        switch (wParam)
        {
        case VK_ESCAPE:
            PostQuitMessage(0);
            return 0;
        }
    }

    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    };

    return 0;
}
}


texts:
The following works fine and I'm not having to repeat any commands once logic is evaluated. However, it feels as though I'm doing a lot of seperate checks. I'm wondering if I could do this more efficiently?

#!/bin/bash

#The script can have 0, 1 or 2 input parameters
#parameter $1 can be one of 4 values ('foo','bar','chu','test')
#parameter $2 can only be 'test' and only if $1 is present and not 'test'

if ( [ $# == 1 ] && [ $1 == 'test' ] ) || ( [ $# == 2 ] && [ $1 != 'test' ] && [ $2 == 'test' ] ); then
    echo 'enable testing'
fi

if [ $# == 0 ] || ( [ $# == 1 ] && [ $1 == 'test' ] ); then
    echo 'do everything'
    exit 0
fi

if ( [ $# == 1 ] && [ $1 != 'test' ] ) || ( [ $# == 2 ] && [ $2 == 'test' ] ); then
    case "$1" in
        'foo')
            echo 'only do foo'
            exit 0
            ;;
        'bar')
            echo 'only do bar'
            exit 0
            ;;
        'chu')
            echo 'only do chu'
            exit 0
            ;;
        *)
            echo 'not valid'
            exit 1
    esac
else
    echo 'not valid'
    exit 1
fi

exit 0


texts:
I have from a recommendation on my other question here:

My other review post

Developed a truncate plugin, and was wondering if you guys could help me improve it or see where I have gone wrong.

Plugin code:

$.fn.vishTrunc = function(options) {

    var settings = $.extend({
            size: 100,
            omission: '...',
        }, options);

    return this.each(function() {

        var elements = $(this),
            regex    = /\s+/,
            init     = function() {
                elements.each(function() {
                var textDefault = $(this).text();

                    if (textDefault.length > settings.size) {
                        var words = textDefault.trim().split(regex).slice(0,settings.size);
var replacement = $("<p class='replacement'/>").text(words.join(" ") + settings.omission);

        $(this).parent().find('.read-more').click(function(){
   if($(this).text() === 'Read More'){
    replacement.hide();
    $(this).parent().find('p:eq(1)').show();
   } else if($(this).text() === 'Read Less'){
       replacement.show();
    $(this).parent().find('p:eq(1)').hide();
   }
    $(this).text(function(i,old){
    return old==='Read More' ?  'Read Less' : 'Read More';
});
return false
});

$(this).before(replacement);
$(this).hide();

                    }
                });
            };
        init();
    });
};


texts: Simple anagram game with names of colors

texts:
This is a very simple anagram game that plays only with names of colors.

I tried to focus on code design.  I also wanted it to support further updates.  But, my init seems smelly and you will notice it, especially in the main loop.

I was wondering about my naming and commenting/docstrings.  I need strong criticism here, without any mercy.

This is the module I've created with the only class:

class AnagramGame:

    def __init__(self, words=None, rword=None, inp=None,
                 anagram=None, is_corr_word=False):
        self._words = None
        self._rword = rword # Stands for random word
        self._anagram = anagram
        self._inp = inp # User input
        self._is_corr_word = is_corr_word # Stands for correct word bool

    def get_words(self):
        return self._words

    def set_words(self, filename):
        in_file = open(filename, 'r')
        self._words = [in_line.rstrip('\n')
                       for in_line in in_file.readlines()]
        in_file.close()

    def del_words(self):
        del self._words

    words = property(get_words, set_words, del_words)

    def get_rword(self):
        return self._rword

    def set_rword(self, sequence):
        import random
        self._rword = random.choice(sequence)

    def del_rword(self):
        del self._rword

    rword = property(get_rword, set_rword, del_rword)

    def get_anagram(self):
        return self._anagram

    def set_anagram(self, sequence):
        import random
        self._anagram = ''.join(random.sample(sequence, len(sequence)))

    def del_anagram(self):
        del self._anagram

    anagram = property(get_anagram, set_anagram, del_anagram)

    def get_is_corr_word(self):
        return self._is_corr_word

    def set_is_corr_word(self, boolean):
        self._is_corr_word = boolean

    def del_is_corr_word(self):
        del self._is_corr_word

    is_corr_word = property(get_is_corr_word, set_is_corr_word,
                            del_is_corr_word)

    def ask_input(self, prompt=''):
        self._inp = input(prompt)

    def check_input(self, prompt_corr, prompt_incorr):
        if self._inp == self.rword:
            print(prompt_corr, end='')
            self._is_corr_word = True
            return self._is_corr_word
        else:
            print(prompt_incorr, end='')
            self._is_corr_word = False
            return self._is_corr_word

And this is the main program:

def main():
    import games

    print("Anagram Mini Game", "\n")

    while True:
        Angrm = games.AnagramGame() # Reset all attributes
        Angrm.words = 'colors.txt' # Load words
        Angrm.rword = Angrm.words # Extract a word
        Angrm.anagram = Angrm.rword # Create anagram of the word

        print("Try build an anagram of this shuffled color name: ", Angrm.anagram)

        Angrm.ask_input("Give it a try - ")
        Angrm.check_input("GG beast", "Wrong - ") # Not indent after impact prompts
        while not Angrm.is_corr_word:
            Angrm.ask_input()
            Angrm.check_input("GG beast", "Wrong - ")

        print("\n\n") # Indent for a new game

if __name__ == '__main__':
    main()


texts:
I'm learning C++, and would like more experienced folks to review my code, and point out what could be improved/changed.
Here's the problem that should be solved (taken from Kattis Securedoors)

You need to write a simple software auditor for tracking employees
entering and exiting your building using their access cards (each card
uniquely identifies the employee holding the card). Your software
needs to look at the access log and determine if there are any
anomalies. There are two types of anomalies your software should
detect:

a user entering the building when, according to the log, they are
already supposed to be in the building
a user exiting the building
when, according to the log, they are not supposed to be in the
building

When your software sees someone enter a building (even if
it’s an anomaly), that person is assumed to be inside the building
from that point on, until he exits. Similarly, if your software sees
someone exit the building (even if it’s an anomaly), that person is
assumed to not be in the building from that point on, until he enters
again. At the beginning of the log, everyone is assumed to be outside
the building.
Input
Input Input starts with a number 1≤n≤10001≤n≤1000 indicating the
length of the log. This is followed by nn lines, each line describing
either an entry or exit by an employee. Each description is of the
form ‘entry name’ or ‘exit name’, where name is a string of up to 20
uppercase and/or lowercase characters (a-z).
Output
For each person’s entry or exit, print the name of the person,
followed by entered or exited. If the action is anomalous, print
(ANOMALY) afterward.
Sample Input 1
8
entry Abbey
entry Abbey
exit Abbey
entry Tyrone
exit Mason
entry Demetra
exit Latonya
entry Idella

Sample Output 1
Abbey entered
Abbey entered (ANOMALY)
Abbey exited
Tyrone entered
Mason exited (ANOMALY)
Demetra entered
Latonya exited (ANOMALY)
Idella entered

Here's my code (working sample)
#include <iostream>
#include <unordered_map>
#include <string>

class UserRegistry {
public:
  void UserEntered(const std::string& user) {
    RegisterUserAction(user, "entered");
  }

  void UserExited(const std::string& user) {
    RegisterUserAction(user, "exited");
  }

private:
  void LogAction(const std::string& user, const std::string& action, bool is_anomaly = false) {
    std::cout << user << " " << action << (is_anomaly ? " (ANOMALY)" : "") << std::endl;
  }

  void RegisterUserAction(const std::string& user, const std::string& action) {
    bool anomaly = false;
    if (action == "entered" && registry[user] % 2 == 1) {
      anomaly = true;
    }

    if (action == "exited" && registry[user] % 2 == 0) {
      anomaly = true;
    }

    if (!anomaly)
      registry[user]++;

    LogAction(user, action, anomaly);
  }

private:
  std::unordered_map<std::string, int> registry;
};

int main() {
  UserRegistry registry;
  int log_length;
  std::cin >> log_length;
  for (int i = 0; i < log_length; ++i) {
    std::string user, action;
    std::cin >> action >> user;

    if (action == "entry")
      registry.UserEntered(user);
    else if (action == "exit")
      registry.UserExited(user);
  }

  return 0;
}


texts: Yet another OpenGL Shader: the Builder pattern and lifetime management

texts:
I've noticed that whenever a shader program class is implemented (from some questions on this site, as well as more reputable implementations), that:

The class tries to do too much. Binding to the current context, setting attribute variable values, and much more.
Use the JavaBeans pattern in one form or another, allowing the shader program to be in an invalid or incomplete state. For example, in between addShaderFromSource calls, the program is only partially built, and not usable.

My ideal shader program class would do much less; its purpose would just be to manage the lifetime of a shader program object, while maintaining a valid state throughout the object's lifetime (either a zero program or a valid, linked program), and the solution I came up with to achieve this uses the builder pattern.

void deleteAttachedShaders(GLuint programId) {
    constexpr GLsizei MAX_SHADER_COUNT = 5;
    GLuint shaderIds[MAX_SHADER_COUNT];
    GLsizei shaderActualCount;
    glGetAttachedShaders(programId, MAX_SHADER_COUNT, &shaderActualCount, shaderIds);

    for(int i = 0; i < shaderActualCount; ++i) {
        glDetachShader(programId, shaderIds[i]);
        glDeleteShader(shaderIds[i]);
    }
}

class GLShaderProgram
{
public:

    class Builder {
    public:
        Builder() : linked_(false) {
            programId_ = glCreateProgram();
        }

        Builder &addShaderFromSource(std::string const &shaderSource, GLenum shaderType) {
            char const *shaderCStr = shaderSource.c_str();
            GLuint shaderId = glCreateShader(shaderType);
            glShaderSource(shaderId, 1, &shaderCStr, nullptr);
            glCompileShader(shaderId);
            glAttachShader(programId_, shaderId);
            return *this;
        }

        Builder &addShaderFromFile(std::string const &shaderFile, GLenum shaderType) {
            std::ifstream fileName(shaderFile);
            std::istreambuf_iterator<char> fileBegin(fileName), fileEnd;
            std::string fileContents(fileBegin, fileEnd);
            return addShaderFromSource(fileContents, shaderType);
        }

        GLShaderProgram linkProgram() {
            glLinkProgram(programId_);
            GLShaderProgram theProgram(programId_);
            deleteAttachedShaders(programId_);
            linked_ = true;
            return theProgram;
        }

        ~Builder() {
             if(!linked_) {
                 glDeleteProgram(programId_);
             }
         }
    private:
        GLuint programId_;
        bool linked_;
    };

    GLShaderProgram() : programId_(0) { }

    GLShaderProgram(GLShaderProgram &&other) {
        *this = std::move(other);
    }

    GLShaderProgram &operator=(GLShaderProgram &&other)
    {
        programId_ = other.programId_;
        other.programId_ = 0;

        if (other.programId_ != 0) {
            glDeleteProgram(other.programId_);
        }

        return *this;
    }

    ~GLShaderProgram() {
        glDeleteShader(programId_);
    }

    GLuint programId() const { return programId_; }

    GLShaderProgram(GLShaderProgram const &other) = delete;
    GLShaderProgram &operator=(GLShaderProgram const &other) = delete;
private:
    GLShaderProgram(GLuint programId) : programId_(programId) { }
    GLuint programId_;
};

Example usage:

auto shaderProgram = GLShaderProgram::Builder()
    .addShaderFromFile("vertex.glsl", GL_VERTEX_SHADER)
    .addShaderFromFile("fragment.glsl", GL_FRAGMENT_SHADER)
    .linkProgram();

glUseProgram(shaderProgram.programId());

Any comments on the code's safety/quality would be appreciated.


texts: Can I make my render method more efficient?

texts:
I get great FPS with this as is, but I'm a performance freak and I don't know AffineTransform or the Java graphics libraries very well. I'm sure there is something I could be doing differently to make this faster, but I can't think of anything, other than it looks like the scale transformation gives me a big performance hit, probably because of the algorithm Graphics2D uses to draw the scaled pixels. I'd be fine with it using a different algorithm that doesn't blend colors if that would make things run faster, but I don't know where to even begin to try to do that.

I dumbed down my code to give you a good idea of what's going on (I hope). I'm only concerned about the render method.

public BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
public Graphics2D graphics = image.createGraphics();

public void render(BufferedImage img, Vector2 center, Vector2 offset, double rotation, Vector2 scale) {
    graphics.setTransform((AffineTransform) defaultTransform.clone());
    graphics.rotate(rotation, center.x, center.y);
    graphics.scale(scale.x, scale.y);
    graphics.translate(center.x / scale.x + offset.x, center.y / scale.y + offset.y);
    graphics.drawImage(img, null, 0, 0);
}

public class Vector2 {
    double x = 0.0, y = 0.0;
}


texts: Convert a double list to a grouped string

texts:
The program has an input a list of doubles and the output needs to be a string containing the list values grouped by their value. The list values will be grouped if they are equal. Something like: input 9,77,5,5,31 => output 9 77 2*5 31

I created an algorithm in C# (in Java I think that is almost the same) for this but I am not sure if it can be improved regarding its speed or code quaility, or if it has some bugs that I could not see. The algorithm having also some more input, output examples is below.

    List<double> input = new List<double> { 11, 32, 32, 43}; // output 11 2*32 43
    //List<double> input = new List<double> { 11, 11, 43, 43 }; // output 2*11 2*43
    //List<double> input = new List<double> { 10, 11, 12, 13, 14, 15, 16 }; // output 10 11 12 13 14 15 16
    //List<double> input = new List<double> { 11, 11, 11, 11, 11 }; // output 5 * 11
    //List<double> input = new List<double> { 11, 11, 32, 22, 22, 22, 4, 10, 10 }; // output 2*11 32 3*22 4 2*10

    string listAsString = string.Empty;
    double nextElem = double.MinValue;
    for (int i = 0; i < input.Count; i++)
    {
        double currentElem = input[i];

        if (i + 1 < input.Count)
        {
            nextElem = input[i + 1];
        }

        int equalCount = 0;
        while (currentElem.Equals(nextElem) && i < input.Count)
        {
            equalCount++;
            i++;
            currentElem = nextElem;

            if (i < input.Count)
            {
                nextElem = input[i];
            }
        }

        if (equalCount < 2)
        {
            listAsString += currentElem + " ";
        }
        else
        {
            listAsString += equalCount + "*" + currentElem + " ";
            i--;
        }
    }

    Console.WriteLine(listAsString);

Please let me know if you noticed some bugs or see some improvements that can be done.

Also if you know another implementation of this requirement please add it so that a comparation regarding results, speed, code quality between the algorithms can be done... and find the best way to handle this.


texts:
I have written a script that run in WingFTP Server which has a Lua scripting engine built in. The script recursively deletes empty folders except the specified root folder.

--Walks a file tree and delete empty folders except the root folder
function EmptyFolderDeleter(options)
    local rootPath = options.path
    local path = options.path

    function walk(path)
        local currentPath = path

        --cycle through the current directory, walking directories
        for dir in c_GetDir(currentPath) do
            local fullPath = currentPath..dir.."/"
            walk(fullPath)
        end

        --if we've got this far then we're at the bottom of the tree
        --there are no more directories to visit
        --now check if there is ANYTHING (file or folder) in the current folder
        local empty = true
        for isdir, file in c_GetFileDir(currentPath) do
            empty = false
        end

        --now check the 'empty' flag and if the folder is the root
        if empty == true and currentPath ~= rootPath then
            c_RemoveFileDir(currentPath)
        end

    end
    walk(path)
 end

The script uses three custom Lua functions that are built into WingFTP:

c_GetDir() = an iterator that returns directory names as string

c_GetFileDir() = an iterator that returns directory and file names as strings. Also returns a boolean whether the returned string is directory or not.

c_RemoveFileDir() = Deletes the specified file or folder

My script can be called like so like so:

local root = "D:/Clients/"
for dir in c_GetDir(root) do
    EmptyFolderDeleter{path=root..dir.."/"}
end

Is there is simpler or more efficient way to recursively delete empty sub folders in Lua?

Is there anything I can do to improve code readability?


texts:
Here's a merge sort I wrote trying to learn Scheme.

(define mergesort
  (lambda (l cmp)
    (define merge
      (lambda (left right)
        (cond
          ((null? left) right)
          ((null? right) left)
          ((cmp (car left) (car right)) (cons (car left) (merge (cdr left) right)))
          (else (merge right left)))))
    (define split
      (lambda (l)
        (define splitr
          (lambda (l left right)
            (if (null? l)
                (list left right)
                (splitr (cdr l) right (cons (car l) left)))))
        (splitr l '() '())))
    (cond
      ((null? l) l)
      ((null? (cdr l)) l)
      (else (let* ((parts (split l))
                   (left (car parts))
                   (right (cadr parts)))
              (merge (mergesort left cmp)
                     (mergesort right cmp)))))))

I know there's already a merge sort question on code review. Frankly, that approach has some nuances I'm not sure I'm prepared to understand yet. So here's my much more naïve approach.

So, keeping in mind I'm pretty much still an FP newbie (so if I don't understand your critique, I'll ask followup questions) and I may have missed some opportunities to do things "the scheme way", how did I do?


texts: Merge sort implementation with various improvements

texts:
So I was working on merge sort today, and was trying to speed it up. I would like your opinion on the implementation and if it's possible to make it faster. Besides that I was wondering if there are any mistakes that i am making code wise, things that are considered a bad practice.

I like making algorithms for fun, and then when i make them I always try to improve them. One thing that I have noticed which i couldn't wrap my head around was that when you give a reverse sorted array as input it works faster than when you don't.

public static void mergeSort(int[] array) {
    mergeDivider(array,0,array.length-1);
}

private static void mergeDivider(int[] array, int lowBound, int highBound) {
    if(lowBound < highBound) {
        int middle = (lowBound + highBound)/2;

        if((highBound - lowBound) <= 43){
            //Found online that insertion sort is faster for n <= 43
            mergeSortInsertionSortSpeedUp(array,lowBound,highBound);
        } else {
            //Normal divide and conquer
            mergeDivider(array, lowBound, middle);
            mergeDivider(array, middle + 1, highBound);

            if(array[middle] > array[middle + 1]){
                mergeSortMerger(array, lowBound, middle, highBound);
            }
        }
    }
}

//Merge method
private static void mergeSortMerger(int[] array, int lowBound, int middle, int highBound) {
    //Doesn't make seperate copies for left and right only makes a temporary array
    int left_index = lowBound, right_index = middle + 1,temp_index = 0;
    int[] temp_holder = new int[highBound - lowBound + 1];

    while(left_index <= middle && right_index <= highBound){
        if(array[left_index] < array[right_index]){
            temp_holder[temp_index++] = array[left_index++];
        } else {
            temp_holder[temp_index++] = array[right_index++];
        }
    }

    while(left_index <= middle){
        temp_holder[temp_index++] = array[left_index++];
    }
    while(right_index <= highBound){
        temp_holder[temp_index++] = array[right_index++];
    }

    //Put everything in the original array
    for(int x = lowBound, k = 0; x <=highBound;x++,k++){
        array[x] = temp_holder[k];
    }
}

private static void mergeSortInsertionSortSpeedUp(int[] array, int left, int right){
    for(int x = left; x <= right;x++){
        int temp = array[x];
        int before = x - 1;
        while(before >= left && array[before] > temp){
            array[before+1] = array[before];
            before--;
        }
        array[before+1] = temp;
    }
}


texts:
This is the code I am using for a distributed system. The code will be used to allow the server to send parts of a (really big) document which will be processed by the connected clients. Please tell me what things would make it more efficient and if there are any security issues that I can correct without addition of an auth library.

#include<stdio.h>
#include<string.h> //strlen
#include<stdlib.h> //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<unistd.h> //write
#include<pthread.h> //for threading , link with lpthread

void *connection_handler(void *);

int main(int argc , char *argv[]) {
    int socket_desc , client_sock , c;
    struct sockaddr_in server , client;
    //Create socket
    socket_desc = socket(AF_INET , SOCK_STREAM , 0);
    if (socket_desc == -1) {
        printf("Could not create socket");
    }
    puts("Socket created");
    //Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons( 8888 );
    //Bind
    if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0) {
        //print the error message
        perror("bind failed. Error");
        return 1;
    }
    puts("bind done");
    //Listen
    listen(socket_desc , 3);
    //Accept and incoming connection
    puts("Waiting for incoming connections...");
    c = sizeof(struct sockaddr_in);

    pthread_t thread_id;

    while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) ) {
        puts("Connection accepted");
        if (pthread_create( &thread_id , NULL , connection_handler , (void*) &client_sock) < 0) {
            perror("could not create thread");
            return 1;
        }
        //Now join the thread , so that we dont terminate before the thread
        //pthread_join( thread_id , NULL);
        puts("Handler assigned");
    }

    if (client_sock < 0) {
        perror("accept failed");
        return 1;
    }
    return 0;
}
/*
* This will handle connection for each client
* */
void *connection_handler(void *socket_desc) {
    //Get the socket descriptor
    int sock = *(int*)socket_desc;
    int read_size;
    char *message , client_message[2000];
    //Send some messages to the client
    message = "Greetings! I am your connection handler\n";
    write(sock , message , strlen(message));
    message = "Now type something and i shall repeat what you type \n";

    write(sock , message , strlen(message));
    //Receive a message from client
    while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 ) {
        //end of string marker
        client_message[read_size] = '\0';
        puts (client_message);
        //Send the message back to client
        write(sock , client_message , strlen(client_message));
        //clear the message buffer
        memset(client_message, 0, 2000);
    }

    // system ("cd; chmod +x script.sh;./script");

    if(read_size == 0) {
        puts("Client disconnected");
        fflush(stdout);
    }
    else if(read_size == -1) {
        perror("recv failed");
    }
    return 0;
}


texts:
Background: A client side I made recently has a component that is made from several (20+) rss-feeds, and the feeds are mashed into one using FreshRSS hosted on our servers. For some reason, FreshRSS sorts it in a weird order instead of the standard date latest to oldest.

So the output looks weird with the latest post that has timestamp for today, but the second post has timestamp for last week, and the third again for today.

So I'm capturing the output with output buffer, storing the output in an array and then storing the output array key in another array that will get sorted by date. What could I do better?

<?php

$feed = file_get_contents("secret-feed-url");

$rowArray = array();
$sortArray = array();

foreach($feed->channel->item as $item){

  ob_start();

  $media = ucfirst(str_replace([".fi", ".com", ".net"], "", parse_url($item->link, PHP_URL_HOST)));
  $date = date("d.m.Y", strtotime($item->pubDate));

  ?>

      <a href="<?php echo $item->link; ?>" target="_blank" rel="noopener">
        <?php echo $item->title; ?>

          <?php echo $media . " &bull; " . $date; ?>

    <?php echo $media; ?>
    <?php echo $date; ?>

  <?php

  $row = ob_get_clean();

  $rowArray[] = $row;

  end($rowArray);
  $rowKey = key($rowArray);

  $sortArray[] = [strtotime($item->pubDate), $rowKey];

}

usort($sortArray, function($a, $b){
  return $a[0] - $b[0];
});

$sortArray = array_reverse($sortArray);

$counter = 0;

foreach($sortArray as $row){

  if($counter > 10){
    break;
  }

  echo $rowArray[$row[1]];
  $counter++;
}

I could store the "output" in a variable instead of using output buffer, but that would result in ugly code & template that is pain to update compared to this. I'm not too conserned about performance, as this is cached data.

Is there a better method for sorting this? I've done this several times on several sites, but it's usually a 1-time operation so using a framework like Symfony is a bit overkill.


texts: Basic demonstration of sprite class in pygame

texts:
I recently created a general purpose sprite class that allows me to easily create and render sprites to the screen, and test for collisions among other things. That class can be found here. So in order to both test and demonstrate the class I've created this simple program that allows you to move around a simple environment, whilst showing off a lot of the features of the class.

So here's the program that I've created to test the class:

import os, sys, pygame, classes.sprite
from pygame.locals import *
from math import *

pygame.init()

path, fname = os.path.split(__file__)
path        = os.path.join(path, 'data')

WIDTH  = 800
HEIGHT = 600
SCREEN = pygame.display.set_mode((WIDTH,HEIGHT))
CLOCK  = pygame.time.Clock()
FPS    = 30
ICON   = pygame.image.load(os.path.join(path, 'Skull.png')).convert_alpha()
ICON   = pygame.transform.scale(ICON, (32, 32))
FONT   = pygame.font.SysFont('Lucida Console', 30)
tick   = 0

classes.sprite.init(SCREEN, FPS)

pygame.display.set_icon(ICON)
pygame.mouse.set_visible(True)
pygame.display.set_caption('Game')

####------Colours------####
DARKGREEN = (  0, 64,   0)
DARKGREY  = ( 64,  64,  64)
GREEN     = (  0, 128,   0)
SILVER    = (192, 192, 192)
####-------------------####

def print_to_screen(text, position = (0, 0), centered = False, colour = (255, 255, 255)):
    '''Prints text to the screen'''
    FONT = pygame.font.SysFont(font, size)
    label = FONT.render(str(text), 1, colour)
    if centered == True:
        position = label.get_rect(center = position)
    SCREEN.blit(label, position)

def main():
    Player  = classes.sprite.Sprite(200, 150,  50,  50)
    Player.set_image('Skull.png', scale = 5)

    Box_1   = classes.sprite.Sprite(300, 275,  50,  50, SILVER)
    Box_2   = classes.sprite.Sprite(450, 275,  50,  50, SILVER)

    Box_2.point_in_direction(90)

    coins = [classes.sprite.Sprite(x, y, 36, 50) for x, y in [[382,  50], [382, 275], [382,  500]]]
    for coin in coins: coin.set_animation(['Coin1.png', 'Coin1.png','Coin2.png', 'Coin3.png'], fps = 6, scale = 0.89)
    coin_group = classes.sprite.SpriteGroup(coins)

    walls = classes.sprite.createLevel('Tile map.txt', colour = GREEN)

    speed = 5
    coin_count = 0

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                print('Quit the game...')
                pygame.quit()
                sys.exit()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    print('Quit the game...')
                    pygame.quit()
                    sys.exit()

        SCREEN.fill(DARKGREY)
        print_to_screen('Coins: ' + str(coin_count), colour = SILVER)

        if Box_1.mouse_click() or Player.rect_collide([Box_1]):
            Player.move(speed, walls.sprites)
            Box_1.render(colour = DARKGREEN)
        else:
            Player.move(speed, walls.sprites + [Box_1])
            Box_1.render(colour = GREEN)

        if coins[0].Collect(Player): coin_count += 1
        if coins[1].Collect(Player): coin_count += 1
        if coins[2].Collect(Player): coin_count += 1

        Box_2.move_in_direction(1)
        if Box_2.rect_collide(walls.sprites): Box_2.turn(180)

        Box_2.render()
        walls.draw()
        coin_group.draw()

        if Player.mouse_click(): Player.point_in_direction(90)
        elif Player.mouse_hover(): Player.turn(5)
        else: Player.point_in_direction(0)

        if Player.rect_collide([Box_2]):
            Box_2.render(RED)
            Print('Hello', (400, Box_2.rect.centery), centered = True, colour = SILVER, font = 'Lucida Console')
            Player.point_towards(sprite = Box_1)
        else:
            Box_2.render(SILVER)

        Player.wrap()
        Player.render()

        pygame.display.update()
        CLOCK.tick(FPS)

if __name__ == '__main__':
    main()


texts: Printing the days of the week for every day this year

texts:
@chux pointed out that my attempted solution contained several problems.  Since I screwed that up so badly, I figure that I should put my revised solution up for review.

#include <stdio.h>
#include <time.h>

/**
 * The current year (number of years since 1900)
 */
static int this_year(void) {
    time_t now = time(NULL);
    struct tm thetime;
    localtime_r(&now, &thetime);
    return thetime.tm_year;
}

static struct tm jan1(int yy) {
    struct tm t = { 0 };
    t.tm_year = yy;
    t.tm_mday = 1;
    t.tm_isdst = -1;
    return t;
}

int main(void) {
    int yy = this_year();

    for (struct tm t = jan1(yy); mktime(&t), t.tm_year == yy; t.tm_mday++) {
        char buf[80];
        if (!strftime(buf, sizeof buf, "%m/%d/%Y is a %A", &t)) {
            return 1;   // Unexpected failure
        }
        puts(buf);
    }
}

Concerns include standards compliance, portability, and correctness in all possible time zones.  If possible, a more succinct way to obtain the current year and January 1 of the current year would be appreciated.


texts:
I am trying to extract names from a body of text to use as stopwords. I tried a few different approaches to identifying names (or proper nouns in general) below. The second approach is much faster than the first, but is admittedly a much more naïve approach (misses out on names like 'PETER' or misspellings like 'jOHN'). Specifically, I'm looking for ways to improve the extract of names (places, people, etc.), but not sacrifice speed. Most of nltk has been pretty bulky, so if there's a better 'naïve' approach to the one I use below, I would appreciate any input.

I've generated some random strings below for demonstration.

import random, string
from time import time
from nltk import pos_tag

def randomword(length):
   return ''.join(random.choice(string.ascii_letters) for i in range(length))

def remainder_lower(string):
    if not string[0].isupper():
        return False
    for letter in string[1:]:
        if letter.isupper():
            return False
    return True

def has_excluded_elements(string, to_exclude):
    for letter in string:
        if letter in to_exclude:
            return True
    return False

# generate 50000 strings with four words in each string
words = [" ".join(randomword(10) for y in range(4)) for x in range(50000)]

# 2 minutes on my machine to run
pos_tag_words = [word for row in words for word in pos_tag(set(row.split())) if word[1] == 'NNP']

# 0.2 seconds on my machine
possible_names1 = [word for row in words for word in set(row.split()) \
                   if remainder_lower(word) and not has_excluded_elements(word, string.punctuation)]


texts:
How well does this code limit security problems when uploading images to the server?

<?php

$filename = $_FILE['inputfile']['name'];
$upload_path = 'images/';
//extract extension
$ext = strtolower(substr($filename, strrpos($filename, '.') + 1));

// return mime type ala mimetype extension
$finfo = finfo_open(FILEINFO_MIME_TYPE);

//get MIME type of the given file
$mime = finfo_file($finfo, $filename);
//close finfo
finfo_close($finfo);

if (is_uploaded_file($_FILES['inputfile']['tmp_name'])) {
    //first check: file extension and mime type
    if(!in_array($ext, array('jpeg', 'jpg', 'gif', 'png')) && !in_array($mime, array('image/jpeg', 'image/gif', 'image/png')) ){
     die("Error1: Invalid Image type");
    }

    //create image according to MIME type

    //first: JPEG and JPG
    if($ext == 'jpeg' || $ext == 'jpg'){
       //move_uploaded_file ignored because no need to use it
       $im = @imagecreatefromjpeg($_FILE['inputfile']['tmp_name']);
       if($im){
          $createimage = imagejpeg($im, $upload_path.$_FILE['inputfile']['name']);
          if(!$createimage){
            die("Error3: Can't create image!");
          }
          //last check
          $filecontent = file_get_contents($upload_path.$_FILE['inputfile']['name']);

          //clean the file from any php code
          //changed
          while(preg_match('#<\?php|\?>|<\?#i', $filecontent)){
            $filecontent = str_replace(array("<?php", "<?", "?>"), "", $filecontent);
          }
          $handle = fopen($upload_path.$_FILE['inputfile']['name'], "wb");
          fwrite($handle, $filecontent);
          fclose($handle);
       }
       else{

        die("Error2: Invalid Image Detected");

       }
    }

}
?>

Edit:

          while(preg_match('#<\?php|\?>|<\?#i', $filecontent)){
            $filecontent = str_replace(array("<?php", "<?", "?>"), "", $filecontent);
          }


texts: Extracting emails from a file and writing them to another file

texts:
The code below works fine for me.  Is there any way that I can improve this code more? Note: delimiter is single whitespace only for email address.

getmail.py

#!/usr/bin/python

import re

handleone = open("scratchmail.txt", "r")
f1 = handleone.readlines()

handletwo = open("mailout.txt", "a+")

match_list = [ ]

for ArrayItem in f1:

    match_list = re.findall(r'[\w\.-]+@[\w\.-]+', ArrayItem)

    if(len(match_list)>0):

         handletwo.write(match_list[0]+"\r\n")

Input file scratchmail.txt:

tickets.cgi:5141|5141Z4063442957942364067088508|1219588377|1219588377||PND||abc@AABBCC.com|Mjpqafml|JgALKGXCuasMph|
tickets.cgi:358236|358236Z24989798132452492828304439|1433071308|1433071308||PND||xyz.abc@example.com|Edison|CpwxPARuQaqPR|
tickets.cgi:86805|86805Z25422507290694218605033173|1232345784|1232345784||PND||pytest@test.com|Agfaodki|jPdSNVlbXi|
…

Output file mailout.txt:

abc@AABBCC.com
xyz.abc@example.com
pytest@test.com


texts: Parsing of XML in Python using minidom, and inserting data into a database

texts:
I have some XML that I am parsing in Python and I need to insert the data on the database. This is current implementation of my code that is working.

Actual XML:

<JobTechData xmlns="http://tempuri.org/JobTechData.xsd">
  <TechDataParams>
    <ProcessType>IONMILL1</ProcessType>
    <RunNumber>125229</RunNumber>
    <RunType>522</RunType>
    <ToolID>HC_VIM05</ToolID>
    <ProcessTS>2016-01-25-08.06.53.000000</ProcessTS>
    <Recipe>S1280</Recipe>
    <PalletPosition>1</PalletPosition>
    <Target>1280</Target>
    <CumulTarget>0</CumulTarget>
    <CTarget>0</CTarget>
    <SITarget>0</SITarget>
  </TechDataParams>
</JobTechData>

And below is the code im using to parse the XML above.

def split(iterable, where):

    def splitter(acc, item, where=where):
        if item == where:
            acc.append([])
        else:
            acc[-1].append(item)
        return acc
    return reduce(splitter, iterable, [[]])

def insert_runspec(spec):
    cnx = mysql.connector.connect(user = USER,
                                        password = PASSWORD,host = HOST,
                                      database = DB, port = DB_PORT)
    cursor = cnx.cursor()
    params = ['?' for item in spec]
    sql = 'INSERT INTO runspecdata(param_value,param_name,ics_runnum,recipe,batch,tool) VALUES (%s)' % ','.join(params)
    cursor.execute(sql,spec)
    cursor.close()
    cnx.close()

spec = []

rc = doc.getElementsByTagName('Recipe')[0].firstChild.nodeValue
rid = doc.getElementsByTagName('RunNumber')[0].firstChild.nodeValue
tid = doc.getElementsByTagName('ToolID')[0].firstChild.nodeValue

# append specification details to spec list, delimit by '|'
spec.append(int(doc.getElementsByTagName('Target')[0].firstChild.nodeValue))
spec.append('target')
spec.append('|')
spec.append(int(doc.getElementsByTagName('CumulTarget')[0].firstChild.nodeValue))
spec.append('cumul')
spec.append('|')
spec.append(int(doc.getElementsByTagName('CTarget')[0].firstChild.nodeValue))
spec.append('c-target')
spec.append('|')
spec.append('sio-target')
spec.append('|')
spec.append(int(doc.getElementsByTagName('SITarget')[0].firstChild.nodeValue))
spec.append('si-target')
splitspec = split(spec,'|')

ics = 1069

for i in splitspec:
    if any(i):
        i.append(ics)
        i.append(rc)
        i.append(rid)
        i.append(tid)
    t = tuple(i)
    insert_runspec(t)

This is the example data inserted to database.

This is working fine. But as you can see the use of the delimiter isn't so Pythonic. Is there a better way to parse the XML?


texts: Sliding marker on link hover and click with jQuery

texts:
The code I'm bringing forward is for a vertical menu, where I needed a marker to do the following:

When hovering over a link the marker should slide down next to it.
When not hovering over a link the marker should return to the side of the current selected link (the default being the first link).
When a link is clicked the marker should remain next to the clicked link, unless another link is being hovered over.

What I've done in jQuery is add a class ('.staydown0','.staydown1' or '.staydown2') to the marker div ('#slide') when one one of the links ('#menulink1','#menulink2' or '#menulink3') is clicked, and remove any other classes that would have it be situated next to one of the other links.

Then I've set jQuery to add a class ('.movedown0','.movedown1' or '.movedown2') to the marker div ('#slide') when the mouse hovers over one of the links ('#menulink1','#menulink2' or '#menulink3'), and remove the class when the mouse stops hovering over the link.

The code works, but it is redundant. How could I go about abstracting it?

I've already asked a similar question recently where I only had the "hover" part of the menu set up, and  it was solved.

But I am a beginner in javascript and jQuery, and even though I've managed to understand the solution that was offered to me in the previous question, I am at a loss as to how to extrapolate that knowledge to abstracting this more convoluted code.

CODEPEN

HTML(Pug):

.staydown0#slide

#menu
  a.menulink#menulink1(href="#")
    p RED
  a.menulink#menulink2(href="#")
    p BLUE
  a.menulink#menulink3(href="#")
    p GREEN

CSS (Sass)

a
  color: white
  text-decoration: none

#slide
  width: 10px
  height: 30px
  position: absolute
  border-radius: 15px
  transition: 0.3s ease-in-out

#slide.staydown0
  margin-top: 0px
  background-color: red

#slide.staydown1
  margin-top: 40px
  background-color: blue

#slide.staydown2
  margin-top: 80px
  background-color: green

#slide.movedown0
  margin-top: 0px
  background-color: red

#slide.movedown1
  margin-top: 40px
  background-color: blue

#slide.movedown2
  margin-top: 80px
  background-color: green

#menu
  margin-left: 30px

.menulink
  height: 40px
  width: 70px
  display: block

.menulink p
  height: 30px
  width: 70px
  margin: 0px
  border-radius: 15px
  display: flex
  align-items: center
  justify-content: center

#menulink1 p
  background: red
#menulink2 p
  background: blue
#menulink3 p
  background: green

jQuery

$('#menulink1').hover(
  function(){
    $('#slide').addClass('movedown0');
  },
  function(){
     $('#slide').removeClass('movedown0')

});

$('#menulink2').hover(
  function(){
    $('#slide').addClass('movedown1');
  },
  function(){
    $('#slide').removeClass('movedown1')

});

$('#menulink3').hover(
  function(){
    $('#slide').addClass('movedown2');
  },
  function(){
    $('#slide').removeClass('movedown2')

});

///////

$('#menulink1').on(
  'click', function(){
      $('#slide').addClass('staydown0').removeClass('staydown1 staydown2');

});

$('#menulink2').on(
  'click', function(){
    $('#slide').addClass('staydown1').removeClass('staydown0 staydown2');

});

$('#menulink3').on(
  'click', function(){
    $('#slide').addClass('staydown2').removeClass('staydown0 staydown1');

});


texts:
I've progressed with the directory statistics function and want to proceed by making it a class.

Link to the first version of this code: Link

My current state of things:

About my namings:
I first used the name fcount as I wanted to have it stand for files and folders as otherwise, the name would be too long. That's why I made the exception to shorten it. I'm still continuing with your more experienced solution for this.
I wrote pathlib into the function name because I have the same function above it with os.walk as this was my first way to try. But os.walk seem to have problems scanning my network drive as it always returned 0 bytes. Therefore I've chosen pathlib. Hope that makes sense.

About my classes: I'm starting to feel comfortable programming python but as soon as I start to use classes my whole code starts to fall apart and seems to have to be more complex. I know that's just a beginner problem, but as I usually can't solve the issues appearing, I'm careful with that route. I've now rewritten it into a class but facing a few problems now.
I started to try to structure it with the tips from the first CodeReview by writing the file search for-loop into the __init__ function but python was then saying it can't return a value from __init__ so I created a new method named def get_directory_statistics(self, scan_path):.
I'm not sure where to input my scan_path, into the __init__or the first method def get_directory_statistics(self, scan_path):.
Your advice to summarize two lines into one, sadly didn't work for me either return size_and_file_count(size_gb, all_types_count, file_count, folder_count). I couldn't get it to work. It's always saying size_and_file_count is not defined or other Errors.

Optimizing the code: I outlined above why I sadly can't use os.walk for this. So this won't work for me. And C seems at the moment, not like an option as the only programming language I am familiar with is python and I guess it would be a more complex task to program a wrapper and the code itself in C. I think most of it will be I/O bound, yes.

Again I learned a lot from the first answer here on CodeReview!

Below you'll find my solution after going over all the last notes

class get_size_and_file_count:
    """Gets the total size of a given dir and counts how many folders and files are in the given
        path directory and return a file count, folder count and all non hidden files as a sum"""
    def __init__(self, total_size = 0, non_hidden_files_count = 0, file_count = 0, folder_count = 0):
        self.total_size = total_size
        self.non_hidden_files_count = non_hidden_files_count
        self.file_count = file_count
        self.folder_count = folder_count

    def get_directory_statistics(self, scan_path):
        self.root_directory = Path(scan_path)
        for f in self.root_directory.glob('**/*'):
            if f.is_file():
                self.file_count += 1
                self.total_size += f.stat().st_size
                if not f.name.startswith("."):
                    self.non_hidden_files_count += 1
            if f.is_dir():
                self.folder_count += 1

        directory_statistics = [self.total_size, self.non_hidden_files_count, self.file_count, self.folder_count]
        return directory_statistics

    def print_directory_statistics(self):
        print('Directory path to search:     {}'.format(self.root_directory))
        print('Directory size in GB:         {:.2f}GB'.format(self.total_size / 1.0e9))
        print('Amount of non hidden files:   {}'.format(self.non_hidden_files_count))
        print('Amount of files searched:     {}'.format(self.file_count))
        print('Amount of folders searched:   {}'.format(self.folder_count))

result = get_size_and_file_count()
directory_statistics = result.get_directory_statistics("...") # Store directory statistics in var
result.print_directory_statistics()  # Print directory statistics


texts: Accessing Wi-Fi network interface details from Java using netsh

texts:
I am developing a Java program on Windows. I want to access Wi-Fi interface details such as SSID, IP, subnet, enabled or not, connected or not and so on. I am currently trying with using netsh and ipconfig commands.

For example, here is how I get the connected SSID. Is this a good way? Is there any better, easier method? Will this code work with all Windows versions without any problems?

String ssid;
ProcessBuilder builder = new ProcessBuilder(
        "cmd.exe", "/c", "netsh wlan show interfaces");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
    line = r.readLine();
    if (line.contains("SSID")){
        ssid = line.split("\\s+")[3];
        System.out.println(ssid);
        return ssid;
    }
}


texts:
Time for the most original question of the year: writing a FizzBuzz in Haskell!

So here is what I came up with:

fizzBuzz :: [Int] -> [String]
fizzBuzz xs =
    [fizz x | x <- xs]

fizz :: Int -> String
fizz x
    | mod x 15 == 0  = "FizzBuzz"
    | mod x 3 == 0   = "Fizz"
    | mod x 5 == 0   = "Buzz"
    | otherwise      = show x

Then I can call

> mapM_ print $ fizzBuzz [1..15]
"1"
"2"
"Fizz"
"4"
"Buzz"
etc

My questions are:

What are obvious awkwardnesses in this code?
How could I mix fizzBuzz and fizz so that there's only one function?
In fizz, is it possible to use a string buffer so that I get rid of the mod x 15 == 0 guard, taking advantage of its redundancy with mod 3 x == 0 and mod 5 x == 0?


texts: Promise for request/response with timeout

texts:
Below is a piece of code that uses a promise for sending a request to a server, and to wait for an answer. Under normal conditions the server will always respond immediately,

But of course you don't want your code to be stuck forever if a response is missed (e.g. a network issue). So for that reason, it needs a timeout as well.

I usually write this as follows. But it takes quiet a lot of code. Any sugestions ?

new Promise( (resolve, reject) => {
  // the promise is resolved when a predefined response is received.
  const listener = (msg) => {
    const { command } = msg;
    if (command === "pong") resolve();
  };

  try {
    this.addListener(listener);

    // write the command
    this.sendMessage( { command: "ping" });

    // there should be an answer within x seconds
    await new Promise(() => setTimeout(reject, timeout));
  }
  finally {
    this.removeListener(listener);
  }
}

I have been using this as a pattern for nodejs, angular and react code.