texts:
I am uploading and selecting code from my MySQL DB and I have a feeling some of it could be written in a much shorter way but I don't know how. Can someone tell me if this is clean code or if it's too much?
<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

include 'config/connect.php';
$con = new mysqli(...$dbCredentials);

if (isset($_POST['add_execise'])) {
    # code...

    $create_exercise = $con->prepare("INSERT INTO exercises (exercise_name, difficulty) VALUES (?, ?)");
    $create_exercise->bind_param("ss", $_POST['exercise_creation'], $_POST['difficulty']);
    $create_exercise->execute();
}

if (isset($_POST['beginner'])) {
    # code...
    $get_exercises = $con->prepare("SELECT exercise_name, difficulty FROM exercises WHERE difficulty = ?");
    $get_exercises->bind_param("s", $_POST['beginner']);
    $get_exercises->execute();
    $get_exercises->store_result();
    $num_of_rows = $get_exercises->num_rows;
    $get_exercises->bind_result($exercise_selected, $difficulty);
}

if (isset($_POST['intermediate'])) {
    # code...
    $get_exercises = $con->prepare("SELECT exercise_name, difficulty FROM exercises WHERE difficulty = ?");
    $get_exercises->bind_param("s", $_POST['intermediate']);
    $get_exercises->execute();
    $get_exercises->store_result();
    $num_of_rows = $get_exercises->num_rows;
    $get_exercises->bind_result($exercise_selected, $difficulty);
}

if (isset($_POST['advanced'])) {
    # code...
    $get_exercises = $con->prepare("SELECT exercise_name, difficulty FROM exercises WHERE difficulty = ?");
    $get_exercises->bind_param("s", $_POST['advanced']);
    $get_exercises->execute();
    $get_exercises->store_result();
    $num_of_rows = $get_exercises->num_rows;
    $get_exercises->bind_result($exercise_selected, $difficulty);
}
?>

<form action="create.php" method="POST">
    <input type="text" name="exercise_creation" placeholder="exercise">
    <input type="text" name="difficulty" placeholder="difficulty">
    <input type="submit" name="add_execise">
</form>

Choose level of difficulty:
 &nbsp;&nbsp;
<form action="create.php" method="POST">

    <button id="beginner" name="beginner" value="beginner">Beginner</button>

    <button id="intermediate" name="intermediate" value="intermediate">Intermediate</button>

    <button id="advanced" name="advanced" value="advanced">Advanced</button>
</form>

<?php

    while ($get_exercises->fetch()) {
        # code...

        echo $exercise_selected . "
";
    }

?>


texts: Test if a key exists anywhere in a nested object

texts:
I have complex objects containing nested objects. I need to check if a key exists anywhere in the nested object. I wrote this code as a makeshift solution. Is there any other way to search for the key?

function checkKey(obj, key) {
    if(key in obj){
        return obj[key];
    }
    else{
        for (k in obj){
            t = obj[k]
            if(typeof t === "object" && !Array.isArray(t) && t !== null){
                return checkKey(t, key);
            }
        }
    }
    return false
}

Test object:

obj = {
    "l1":"test333",
    "some":{
        "l2":"test2",
        "l22":"test3",
        "other":{
            "l3":["yellow"]
        }
    }
}

Search: checkKey(obj, "l3"); returns ["yellow"]


texts: Format an integer with thousands separator (recursive implementation)

texts:
The function accepts a number n and displays it recursively with commas.

As well as a general code review, I'm interested in suggestions for alternatives to counting to tell when to print the commas.  I tried if(mod%10000 == 0); that works on the first 3 numbers, but after that mod is always a multiple of 10000.

#include <iostream>
using namespace std;

void RecursiveCommas(long long n, int mod = 10, int i = 0);

int main()
{
    RecursiveCommas(123456789);
    return 0;
}

void RecursiveCommas(long long n, int mod, int i){
    if(n%mod==n){ //base case
        if(i%3 == 0 && i != 0)
            cout << (n%mod) / (mod/10) << ",";
        else
            cout << (n%mod) / (mod/10);
    }
    else{
        if(i%3 == 0 && i != 0){ //add commas
            RecursiveCommas(n, mod*10, i+1);
            cout << (n%mod) / (mod/10) << ",";
        }
        else { //no comma needed
            RecursiveCommas(n, mod*10, i+1);
            cout << (n%mod) / (mod/10);
        }
    }
}


texts: Clearing the text when `text select` release

texts:
I required a trigger, whenever the window text selection cleared.
Finally I found this approach.

Using the same id, I have added multiple event handlers, but I am not sure my work is the best.

Is there a better way to do this?

 $('#tenderContent').on('mouseup', '.tenderdocument', function (e) {
    e.stopPropagation();
    if ($.trim(window.getSelection().toString()).length) {
        $('#text').text(window.getSelection().toString());
    }

});

$('#tenderContent').on('mousemove', '.tenderdocument', function (e) {
    e.stopPropagation();
    if (!$.trim(window.getSelection().toString()).length) {
         $('#text').empty();
    }
});

LiveDemo


texts:
I have written this regex to validate an email. It seems to work fine. Can someone advise on the regex used? Does it work properly or can be done in a better way?
pattern=r"^[A-Za-z]+[-_$.A-Za-z]*@[A-Za-z]*\.[A-Za-z]+$"
x=re.search(pattern,"abc.xyz@gmail.com)
print x

Note: I have used x and print as Code Review needs minimum 3 lines of code.


texts: Optimizing my 2D Ising model code in Julia

texts:
I'm just starting to learn Julia, I work primarily in physics and am used to writing most of my code in Fortran90 and occasionally Python for Tensorflow (also Mathematica but that's less relevant). Julia has been recommended to me and I started checking it out; I like it a lot in theory as a middle ground between the speed of Fortran and the syntax of Python. To test it out I wrote a simple 2D Ising model code implementing a basic single-spin-flip Metropolis Monte Carlo algorithm. However, this code runs very slowly compared to an equivalent code in Fortran. Am I doing something wrong which is significantly affecting the performance of the code? I know almost nothing beyond what I've done here. I am using the Juno IDE in Atom on Windows 10. As an aside, I would also like to know how I can make multiple plots in the Atom plot tab, but that's secondary.

using Printf
using Plots

L       = 20             # linear size of lattice
n_sweep = 20             # number of sweeps between sampling
n_therm = 1000           # number of sweeps to thermalize
n_data  = 100            # number of data samples per temperature
temps   = 4.0:-0.3:0.1   # temperatures to sample
e1 = Array(1:n_data)     # array to hold energy measurements (fixed T)
m1 = Array(1:n_data)     # array to hold magnetization measurements (fixed T)
et = []                  # array to append average energy at each T
mt = []                  # "                      magnetizations
s  = ones(Int32,L,L)     # lattice of Ising spins (+/-1)

function measure(i)      # measure i'th sample of energy and magnetization
    en = 0
    m = 0
    for x = 1:L
        for y = 1:L
            u = 1+mod(y,L) # up
            r = 1+mod(x,L) # right
            en -= s[x,y]*(s[x,u]+s[r,y]) # energy
            m  += s[x,y]                 # magnetization
        end
    end
    energy[i] = en
    magnetization[i] = abs(m)
end

function flip(x,y,T) # apply metropolis spin flip algorithm to site (x,y) w/ temp T
    u = 1+mod(y,L)   # up
    d = 1+mod(y-2,L) # down
    r = 1+mod(x,L)   # right
    l = 1+mod(x-2,L) # left
    de = 2*s[x,y]*(s[x,u]+s[x,d]+s[l,y]+s[r,y])
    if (de < 0)
        s[x,y] = -s[x,y]
    else
        p = rand()
        if (p < exp(-de/T))
            s[x,y] = -s[x,y]
        end
    end
end

function sweep(n,T) # apply flip() to every site on the lattice
    for i = 1:n
        for x = 1:L
            for y = 1:L
                flip(x,y,T)
            end
        end
    end
end

for T in temps              # loop over temperatures
    sweep(n_therm, T)       # thermalize the lattice
    energy        = e1      # reset energy measurement array
    magnetization = m1      # same
    for i = 1:n_data        # take n_data measurements w/ n_sweep
        sweep(n_sweep, T)
        measure(i)
    end
    en_ave = sum(energy)/n_data           # compute average
    ma_ave = sum(magnetization)/n_data
    push!(et,en_ave/(L*L))                # add to the list
    push!(mt,ma_ave/(L*L))
    @printf("%8.3f  %8.3f \n", en_ave/(L*L), ma_ave/(L*L))
end

plot(temps,mt) # plot magnetization vs. temperature
#plot(temps,et)


texts: Displaying an arbitrary number of buttons and automatically arranging the buttons

texts:
It is supposed to take an arbitrary number of arguments, turn those arguments into buttons, and arrange those buttons in a way to give each individual button the largest area possible. Is there a better way to do this? Be as thorough as you like.

import sys
import tkinter as tk
import os

from tkinter import *
###functions
def calcRowsAndColumns(area = None):
    if(area==None):
        area = len(sys.argv) -1
    if(area==1):
        return (1,1)
    rectanglePropertiesList = []
    for rows in range(1, area):
        if(area % rows == 0):
            columns = int(area/rows)
            rectanglePropertiesList.append([rows,columns])
    if (len(rectanglePropertiesList) == 1): #This deals with prime numbers
        return calcRowsAndColumns(area+1)
    return tuple(smallestPerimeter(rectanglePropertiesList))

def smallestPerimeter(propertyList):
    return propertyList[propertyList.index(min(propertyList, key=sum))]

def preserve(gFile):
    print(gFile)
    argList.remove(gFile)
    for i in argList:
        os.remove(i)

def relwidth(root):
    return root.winfo_screenwidth()//(len(argList))-20
    #Subtracting 20 to account for padding

def relheight(root):
    return root.winfo_height()//(len(argList))-20
###Code to be executed
rowsAndColumnTuple = calcRowsAndColumns(None)
root = tk.Tk()
root.attributes("-fullscreen", True)
root.config(bg="white")
root.grid()

listButton = []

argList = [i for i in sys.argv[1:]]

for i in argList:
    listButton.append(Button(root, text=i.rpartition(os.sep)[2],
                             font="-size 20", command=lambda x=i: preserve(x),
                             #lambda used here to allow parameters to be passed to the preserve function
                             padx=10, pady=10,
                             bg ="black", fg = "red"))

iterButtons = iter(listButton)

for i in range(rowsAndColumnTuple[0]):
    root.grid_rowconfigure(i, weight=1)
    for j in range(rowsAndColumnTuple[1]):
        root.grid_columnconfigure(j, weight=1)
        try:
            button=next(iterButtons)
        except StopIteration:
            print("reached end of list : ignoring remaining grid cells")
            break
        button.grid(row=i,column=j)

root.update()

for i in listButton:
    i.config(height=relheight(root), width=relwidth(root))
    #This resizes the buttons to the correct size

root.mainloop()


texts: Check which state is activated and render the JSX accordingly

texts:
Just wondering how I can go about doing this more efficiently/make it more visually appealing to the user?

     switch (this.state.selected) {
  case "all":
    styled = this.state.allKeywords.map(keyword =>

           <Input key={Math.random} style={{height: "45px", marginBottom: "20px"}} onClick={this.onKeywordClick} value={keyword} onChange={this.onKeywordChange}></Input>
           <Button key={Math.random} onClick={() => this.deleteKeyword(keyword)} style={{height: "45px", marginLeft: "30px"}}>Delete</Button>

     );
    break;
  case "positive":
      styled = this.state.positive.map(keyword =>

             <Input key={Math.random} style={{height: "45px", marginBottom: "20px"}} onClick={this.onKeywordClick} value={keyword} onChange={this.onKeywordChange}></Input>
             <Button key={Math.random} onClick={() => this.deleteKeyword(keyword)} style={{height: "45px", marginLeft: "30px"}}>Delete</Button>

       );
     break;
  case "negative":
      styled = this.state.negative.map(keyword =>

             <Input key={Math.random} style={{height: "45px", marginBottom: "20px"}} onClick={this.onKeywordClick} value={keyword} onChange={this.onKeywordChange}></Input>
             <Button key={Math.random} onClick={() => this.deleteKeyword(keyword)} style={{height: "45px", marginLeft: "30px"}}>Delete</Button>

       );
     break;
  default:
    console.log("No keyword list mapped");
}


texts: Read data from Google Sheets API and populate a class

texts:
I have data stored in a Google Sheet. The aim of this program controller is to read this data from an MVC controller, and populate a class (Model) with it.

I will skip most of the intermediate functions, to keep the focus on the Google API connection.

My main concern is with the connection, and use of the Google API (could be any API though).

I have doubts about creating a connection object in the controller this way (in particular since I have multiple controllers, that will all create a new API object)
I am new to coding, so any general advice on best coding practices will be welcome

Notes:

The APIKey is stored in the root folder of the project, and called APIKey.json
For reusability reasons (there is a desktop sister-app) sheetData and GoogleAPI classes are in a separate DLL.

Controller:

Function Data(sheetID As String) As ActionResult
    Dim API As New GoogleAPI(Web.HttpContext.Current.Request.PhysicalApplicationPath + "APIKey.json")

    Dim modelData = New sheetData(API, sheetID).Datum

    Return View(modelData)
End Function

sheetData class:

Public Class sheetData
    Public ReadOnly Property Datum As String

    Public Sub New(googleAPIConnection As GoogleAPI, sheetID As String)
       Const dataRange = "Sheet1!A1"
       Datum = googleAPIConnection.GetValuesFromGoogleSheet(sheetID, dataRange)(0)(0)
    End Sub
End Class

GoogleAPI class:

Public Class GoogleAPI
    Friend _credentials As GoogleCredential
    Public Sub New(apikeypath As String)
        Using stream As New FileStream(apikeypath, FileMode.Open, FileAccess.Read)
            _credentials = GoogleCredential.FromStream(stream).CreateScoped(SheetsService.Scope.Drive, SheetsService.Scope.Spreadsheets)
        End Using
    End Sub

    Public Function GetValuesFromGoogleSheet(sheetID As String, requestedRange As String) As IList(Of IList(Of Object))
        Dim service = New SheetsService(New BaseClientService.Initializer() With {
               .HttpClientInitializer = _credentials,
               .ApplicationName = "appName"
                                       })
        Dim request As SpreadsheetsResource.ValuesResource.GetRequest =
            service.Spreadsheets.Values.Get(sheetID, requestedRange)
        Dim requestResponse As ValueRange = request.Execute
        Return requestResponse.Values
    End Function
End Class


texts:
I'm learning Dynamic Programming, following the topcoder guide. I just solved the AvoidRoads challenge. It passes all the test cases, but I don't have much experience, so I don't know if it's good.

  Challenge Description

  Linked description contains images and better illustrates the problem.

  You are standing at the corner with coordinates 0,0. Your destination
  is at corner width,height. You will return the number of distinct
  paths that lead to your destination. Each path must use exactly
  width+height blocks. In addition, the city has declared certain street
  blocks untraversable. These blocks may not be a part of any path. You
  will be given a String[] bad describing which blocks are bad. If
  (quotes for clarity) "a b c d" is an element of bad, it means the
  block from corner a,b to corner c,d is untraversable. For example,
  let's say

width  = 6
length = 6
bad = {"0 0 0 1","6 6 5 6"}

Returns: 252

My Solution:

def allowed(i, j, x, y, banned_set):
    s = "{} {} {} {}"
    options = [
        s.format(i, j, x, y),
        s.format(x, y, i, j)
     ]

    for opt in options:
        if opt in banned_set:
            return False
    return True

def calc(lst, i, j, banned_set):
    result = 0
    if i-1 >= 0 and allowed(i, j, i-1, j, banned_set):
            result += lst[i-1][j]
    if j-1 >= 0 and allowed(i, j, i, j-1, banned_set):
            result += lst[i][j-1]

    return result

def avoid_roads(n, m, banned_set):
    n += 1
    m += 1

    matrix = [[0 for _ in xrange(m)] for _ in xrange(n)]
    matrix[0][0] = 1

    for i in xrange(n):
        for j in xrange(m):
            if i == j == 0:
                continue
            matrix[i][j] = calc(matrix, i, j, banned_set)
    return matrix[-1][-1]


texts: Collecting data from General Ledger accounts lines

texts:
I have a pair of General Ledger accounts to scan for data. I need to find a keyword or phrase from the descriptions and then collect certain bits of data from those lines. The source tables (there are two) are on separate tabs and the data from that needs to populate 5 other tables of data for analysis.

This is the code I have so far but it is exceedingly slow. I would like suggestions to speed up the process. My thought is to load all the data into an array but I am not sure if that would be faster.

Sub Table9052()
Dim i As Integer
Dim wsA As Worksheet: Set wsA = ThisWorkbook.Sheets("QA Data A")
Dim wsK As Worksheet: Set wsK = ThisWorkbook.Sheets("QA Data K")
Dim wsT As Worksheet: Set wsT = ThisWorkbook.Sheets("Tables")
Dim Locker As String
Dim GC As String
Locker = "9052 Electronic Lockers"
GC = "9042 Dunkin Donuts Gift Card"
MBD = "MERCHANT BANKC"
DDSV = "DD STORED VALU"
SS = "STARBUCKS STOR"
ColARow = 3
ColFRow = 3
ColKRow = 3
ColPRow = 3
ColURow = 3

Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
For i = 6 To wsA.Range("C65536").End(xlUp).Row
    Eval = wsA.Cells(i, 4)
    If Eval = Locker Then 'If a locker line copy the cells to ELTable
        wsA.Cells(i, 3).Copy wsT.Cells(ColARow, 1) 'Copy Date to column A
        wsA.Cells(i, 4).Copy wsT.Cells(ColARow, 2) 'Copy Desc to column B
        wsA.Cells(i, 5).Copy wsT.Cells(ColARow, 3) 'Copy Ammt to column C
        wsA.Cells(i, 7).Copy wsT.Cells(ColARow, 4) 'Copy Lodge to column D
        ColARow = ColARow + 1
    End If
    If Eval = GC Then 'If a locker line copy the cells to DDCardTable
        wsA.Cells(i, 3).Copy wsT.Cells(ColPRow, 16) 'Copy Date to column A
        wsA.Cells(i, 4).Copy wsT.Cells(ColPRow, 17) 'Copy Desc to column B
        wsA.Cells(i, 5).Copy wsT.Cells(ColPRow, 18) 'Copy Ammt to column C
        wsA.Cells(i, 7).Copy wsT.Cells(ColPRow, 19) 'Copy Lodge to column D
        ColPRow = ColPRow + 1
    End If
Next i
For i = 6 To wsK.Range("C65536").End(xlUp).Row
    Eval = Left(wsK.Cells(i, 4), 14)
    If Eval = MBD Then 'If a locker line copy the cells to ELTable
        wsK.Cells(i, 3).Copy wsT.Cells(ColFRow, 6) 'Copy Date to column F
        wsK.Cells(i, 4).Copy wsT.Cells(ColFRow, 7) 'Copy Desc to column G
        wsK.Cells(i, 5).Copy wsT.Cells(ColFRow, 8) 'Copy Ammt to column H
        wsK.Cells(i, 7).Copy wsT.Cells(ColFRow, 9) 'Copy Lodge to column I
        ColFRow = ColFRow + 1
    End If
    If Eval = DDSV Then 'If a locker line copy the cells to DDCardTable
        wsK.Cells(i, 3).Copy wsT.Cells(ColKRow, 11) 'Copy Date to column K
        wsK.Cells(i, 4).Copy wsT.Cells(ColKRow, 12) 'Copy Desc to column L
        wsK.Cells(i, 5).Copy wsT.Cells(ColKRow, 13) 'Copy Ammt to column M
        wsK.Cells(i, 7).Copy wsT.Cells(ColKRow, 14) 'Copy Lodge to column N
        ColKRow = ColKRow + 1
    End If
    If Eval = SS Then 'If a locker line copy the cells to DDCardTable
        wsK.Cells(i, 3).Copy wsT.Cells(ColURow, 21) 'Copy Date to column U
        wsK.Cells(i, 4).Copy wsT.Cells(ColURow, 22) 'Copy Desc to column V
        wsK.Cells(i, 5).Copy wsT.Cells(ColURow, 23) 'Copy Ammt to column W
        wsK.Cells(i, 7).Copy wsT.Cells(ColURow, 24) 'Copy Lodge to column X
        ColURow = ColURow + 1
    End If
Next i
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub


texts:
I have the following class:
public class UpdateData {

    public static boolean updateHasMessage(Update update) {
        return update.hasMessage() && update.getMessage().hasText();
    }

    public static boolean updateHasCallbackQuery(Update update) {
        return update.hasCallbackQuery() && (update.getCallbackQuery().getData()!= null);
    }

    public static Long getChatId(Update update) {
        if (updateHasMessage(update)) {
            return update.getMessage().getChatId();
        }
        else if (updateHasCallbackQuery(update)) {
            return update.getCallbackQuery().getMessage().getChatId();
        }
        else {
            return null;
        }
    }

    public static String getUserName(Update update) {
        if (updateHasMessage(update)) {
            return update.getMessage().getFrom().getUserName();
        }
        else if (updateHasCallbackQuery(update)){
            return update.getCallbackQuery().getFrom().getUserName();
        }
        else {
            return null;
        }
    }

    public static String getInputUserData(Update update) {
        if (updateHasMessage(update)) {
            return update.getMessage().getText();
        }
        else if (updateHasCallbackQuery(update)){
            return update.getCallbackQuery().getData();
        }
        else {
            return null;
        }
    }

    public static String getCallBackId(Update update) {
        return update.getCallbackQuery().getId();
    }

    public static Integer getMessageId(Update update) {
        if (updateHasMessage(update)) {
            return update.getMessage().getMessageId();
        }
        else if (updateHasCallbackQuery(update)){
            return update.getCallbackQuery().getMessage().getMessageId();
        }
        else {
            return null;
        }
    }

    public static String getCallBackData(Update update) {
        return update.getCallbackQuery().getData();
    }
}

As you can see I have similar block code in most methods:
if (updateHasMessage(update)) {
    ...
}
else if (updateHasCallbackQuery(update)) {
    ...
}
else {}

They return unique information and have various stuff inside, but this is very similar to code duplication.
Do I need to rewrite this or just stay with it? If need to rewrite, then how?
UPDATE
Update is a Telegram API object.


texts:
I had this question in an interview recently.  Given a sorted array of integers, return a list of those integers squared, with the squares sorted.  So given an array of these numbers:

-5, -3, 1, 2, 4

the result should be this:

1 4 9 16 25

I came up with this solution using Java 8 streams, but is there a way to do this without the call to Array.sort?

public static int[] sortedSquares(int[] arr) {
    arr = Arrays.stream(arr).map(i -> i * i).toArray();
    Arrays.sort(arr);
    return arr;
}


texts:
I decided to redo the first program I wrote (after the hello world thing). So, what it does is to convert a DNA sequence string to an array of strings that represent the amino acids that are made in a cell by ribosomes when that DNA sequence gets used (DNA codon table).

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

char* codon_table[4][4][4] =
{
  {
    {"Phe", "Phe", "Len", "Len"},
    {"Ser", "Ser", "Ser", "Ser"},
    {"Tyr", "Tyr", "Stop", "Stop"},
    {"Cys", "Cys", "Stop", "Trp"}
  },
  {
    {"Len", "Len", "Len", "Len"},
    {"Pro", "Pro", "Pro", "Pro"},
    {"His", "His", "Gln", "Gln"},
    {"Arg", "Arg", "Arg", "Arg"}
  },
  {
    {"Ile", "Ile", "Ile", "Met"},
    {"Thr", "Thr", "Thr", "Thr"},
    {"Asn", "Asn", "Lys", "Lys"},
    {"Ser", "Ser", "Arg", "Arg"}
  },
  {
    {"Val", "Val", "Val", "Val"},
    {"Ala", "Ala", "Ala", "Ala"},
    {"Asp", "Asp", "Glu", "Glu"},
    {"Gly", "Gly", "Gly", "Gly"}
  }
};

int check_nucleobase_string(char* nucleobase_string)
{
  if(nucleobase_string==NULL)
  {
    return 1;
  }
  for(size_t i = 0; nucleobase_string[i] != '\0'; i+=1)
  {
    if(
      nucleobase_string[i] != 't' &&
      nucleobase_string[i] != 'c' &&
      nucleobase_string[i] != 'a' &&
      nucleobase_string[i] != 'g'
    )
    {
      return 0;
    }
  }
  return 1;
}

size_t nucleobase_to_aminoacid(char* nucleobase_string, char*** aminoacid_string)
{
  if(!check_nucleobase_string(nucleobase_string))
  {
    printf("Erroneous input: %s\n", nucleobase_string);
    return 0;
  }

  size_t nucleobase_count ;
  for(nucleobase_count = 0; nucleobase_string[nucleobase_count] != '\0'; nucleobase_count+=1);
  size_t aminoacid_count = nucleobase_count/3;

  (*aminoacid_string) = malloc(aminoacid_count);

  for(size_t i = 0, slow_i = 0; slow_i < aminoacid_count; i+=3, slow_i+=1)
  {
    (*aminoacid_string)[slow_i] =
      codon_table[
        nucleobase_string[i] == 't' ? 0 :
        nucleobase_string[i] == 'c' ? 1 :
        nucleobase_string[i] == 'a' ? 2 :
        nucleobase_string[i] == 'g' ? 3 : -1
      ][
        nucleobase_string[i+1] == 't' ? 0 :
        nucleobase_string[i+1] == 'c' ? 1 :
        nucleobase_string[i+1] == 'a' ? 2 :
        nucleobase_string[i+1] == 'g' ? 3 : -1
      ][
        nucleobase_string[i+2] == 't' ? 0 :
        nucleobase_string[i+2] == 'c' ? 1 :
        nucleobase_string[i+2] == 'a' ? 2 :
        nucleobase_string[i+2] == 'g' ? 3 : -1
      ];
  }

  return aminoacid_count;
}

int main()
{
  printf("Enter DNA sequence in 5' → 3' direction.\n");

  char* input_string = NULL;
  size_t n = 0;
  ssize_t line_length = getline(&input_string, &n, stdin);
  if(line_length == -1)
  {
    printf("Failed to read a line.\n");
    return 0;
  }

  char* nucleobase_string = malloc(line_length);
  memcpy(nucleobase_string, input_string, line_length-1);
  nucleobase_string[line_length-1] = '\0';

  char** aminoacid_string = NULL;
  size_t aminoacid_count = nucleobase_to_aminoacid(nucleobase_string, &aminoacid_string);

  for(size_t i = 0; i < aminoacid_count; i+=1)
  {
    if(i!=0)
    {
      printf(" + ");
    }
    printf("%s", aminoacid_string[i]);
  }
  printf("\n");

  return 0;
};


texts:
I download a page to get it's source code. I then extract the first segment of the page that is between two strings that appear in the source code more than once.

How can my code be improved?

url = "https://www.zapimoveis.com.br/lancamento/apartamento+venda+vl-mariana+zona-sul+sao-paulo+sp+ibirapuera-boulevard+mofarrej-empreendimentos+246m2-391m2/ID-16760/?contato=0"

sourcecode = requests.get(url)
r = sourcecode.text

string1 = '","billing":"'
string2 = '"},"createdDate":"'

start = re.findall(string1, r)
start = start[0]

end = re.findall(string2, r)
end = end[0]

text= r[r.find(start)+len(start):r.rfind(end)]

print(text)


texts: "What is the fastest solution for finding the maximum sum of a subarray?"

texts:
Question

  Given an array, find the longest continuous sub-array which has maximum sum.

My Approach

First, I solved this problem using dynamic programming which effectively solved the problem in \$O(n)\$ time as opposed to the brute force approach. For each iteration, I checked if the sum is less than 0, and if true, I ran a new sum whenever the sum became less than 0.

Also, I kept track of the current maximum in each iteration.

class Solution
{
    public int maxSubArray(int[] nums)
    {
        /*
         * get the array size.
         */
        int size = nums.length;

        /*
         * initialize the variables to the first index of the array.
         */
        int sum = nums[0];
        int max = nums[0];

        /*
         * iterate using a loop from 1 to n-1.
         * set sum to 0 if current is less than 0.
         * for negative results, no need to add sum as the largest sum is the smallest negative number itself.
         * update max if sum is greater.
         */
        for (int i = 1; i < size; i++)
        {
            if (sum < 0)
                sum = 0;

            sum += nums[i];
            if (sum > max)
                max = sum;
        }
        return max;
    }
}

As you can see from the above, I have kept the code as compact as possible. I also stored the array length also in a variable for faster execution. And the solution is linear time.

Issues

When I submit on LeetCode, I am told that my code is only 17% faster as compared to the rest of Java submissions for the same problem.
How do I make this code more optimised (or rather, is there any way to optimise this code even more?)
Is there a better/different approach to this problem?
I haven't used any Java APIs, library functions etc. then could anyone please tell me where is the time being consumed (or rather, which is the most costly operation in my algorithm and is there any way to reduce the costly operation?)

Notes

The solution is correct as it passed all 200 test cases! (It's just that it is slow).

To find the required sub-array, I need to iterate over the array at least once just to see if my sum can be maximised. In such a case, the minimum time has to be linear time and if this observation were true, then all the other faster solutions must run at least linear time. Again, if the above were true, then it means the faster solutions are using techniques to make the execution faster despite it being linear time, right?


texts:
I am using the following VBA to fetch data from an Access database. The query works but there is a lot of information in the database and the response time is very slow, about 30 seconds.

Is there any part of the code that I could optimise or write differently?

Sub test()

Dim strsql1, tr As String
Dim rst As ADODB.Recordset

strsql1 = "SELECT * FROM FP WHERE SUBMISSION_ID = 5683;"

Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ace.OLEDB.12.0; Data Source=\\REDACTED.accdb;"

Set rst = New ADODB.Recordset

rst.Open strsql1, cn, adOpenStatic

End Sub


texts: Python Script to get list of all download links from an FTP based File Hosting URL

texts:
I made a small script to get a list of all download links from an FTP based File Hosting URL. I have tested it on a couple of URLs and it works reasonably well.

Can you please point out mistakes and bad practices, suggest ways to improve, and if possible further generalize the code?

Also, please suggest ways I could use the Python Standard Library instead of Beautiful Soup without sacrificing too much simplicity, if possible.

import requests
from bs4 import BeautifulSoup, SoupStrainer

url = "http://some_ftp_url.net/movies/"

download_links = []
video_file_extensions = ('mkv', 'mp4', 'mpeg4', 'mov', 'avi')

def recursiveUrl(url, depth):
        if depth == 5:
                return url
        elif url.endswith(video_file_extensions):
                download_links.append(url)
                return
        else:
                page = requests.get(url)
                for link in BeautifulSoup(page.text, parse_only=SoupStrainer('a'), features="html.parser"):
                        if (link.has_attr('href') and link.text != '../'):
                                recursiveUrl(url + link['href'], depth + 1)

def getLinks(url):
        page = requests.get(url)

        for link in BeautifulSoup(page.text, parse_only=SoupStrainer('a'), features="html.parser"):
                if (link.has_attr('href') and link.text != '../'):
                        recursiveUrl(url + link['href'], 0)
        return download_links

if __name__ == '__main__':
        getLinks(url)
        for download_link in download_links:
                print('\n')
                print(download_link)


texts: Particle simulator using Python - Why is the NumPy version slower than pure Python?

texts:
This is an interesting example from G.Lanaro's book, Python High Performance. The program is a simple simulator which describes movement of particles based on their positions and angular velocities (x, y, and ang_v attributes of a Particle class). The bottleneck of the program is the evolve method which is initially implemented using pure Python, and then the author tries to show how we can improve the performance of this specific method using NumPy operations.

My problem is that when I compare the run-time of NumPy version (evolve_numpy) versus the pure Python version (evolve), I can hardly see any improvement in terms of runtime; in fact, it seems like pure Python is a bit faster here.

I wrote all of this code myself, based off of what I learned in the book.

The initial version of evolve is as follows

    def evolve(self, dt):
        timestep = .00001
        nstep = int(dt / timestep)
        for i in range(nstep):
            for p in self.particles:
                t_x_ang = timestep * p.ang_v
                norm = (p.x ** 2 + p.y ** 2) ** .5
                p.x, p.y = (p.x - t_x_ang * p.y / norm, p.y + t_x_ang * p.x/norm)

            # repeat for all particles
        # repeat for all time-steps

Here is the NumPy version of the same method,

    def evolve_numpy(self, dt):
        timestep = 0.00001
        nsteps = int(dt / timestep)
        r_i = np.array([[p.x, p.y] for p in self.particles])
        ang_vel_i = np.array([p.ang_v for p in self.particles])
        for i in range(nsteps):
            norm_i = np.sqrt((r_i ** 2).sum(axis=1))
            v_i = r_i[:, [1, 0]]
            v_i[:, 0] *= -1
            v_i /= norm_i[:, np.newaxis]
            d_i = timestep * ang_vel_i[:, np.newaxis] * v_i
            r_i += d_i
            for i, p in enumerate(self.particles):
                p.x, p.y = r_i[i]

To test the runtime of both versions, a benchmark2 function is defined as follows:

def benchmark2(nparts, m):
    particles = [Particle(uniform(-1, 1), uniform(-1, 1), uniform(-1, 1))
                 for i in range(nparts)]
    sim = ParticleSimualtor(particles)
    if m == 1:
        sim.evolve(.1)
    elif m == 2:
        sim.evolve_numpy(.1)
    else:
        raise Exception('not a valid method')

You can access the complete code here: https://gist.github.com/OmidMiresmaeili/2891c4f1ce95f65cfab8ed0469e427d4

My results are as follows:

1min 40s for NumPy version and 1min 29s for Python version

But the author claim (and I understand the reasoning) that the NumPy version runs much faster than the initial version of evolve without any NumPy operations:

This is a figure from page 71 of the book. It shows run-time for different particle size (nparts argument in the benchmark2 function). The author then concludes:

  The plot shows that both the implementations scale linearly with particle size, but the runtime in the pure Python version grows much faster than the NumPy version; at greater sizes, we have a greater NumPy advantage. In general, when using NumPy, you should try to pack things into large arrays and group the calculations using the broadcasting feature.

Now I'm not sure if it is a typo in the book or maybe I am not understanding this correctly. I would appreciate any input you can give me.


texts: Automating A Workflow Using Selenium - Best Way To Fetch Elements & Make Code More Generic

texts:
I'm a newbie to Selenium and I'm trying to get better at it by taking up interview assignments. This YouTube link describes the workflow that needs to be automated.

The following points are worth taking into account.

For your purpose, use your own gmail id/password but make it readable from a file in your project.
Use the fashion photo pasted below as input.

I implemented the following solution and I'd like to know if there's any way to improve it. I'm interested in any changes that can be made, to make the script more robust in addition to any new concepts or tools in Selenium or Python that might make life easier as well as existing concepts and tools that I could implement a whole lot better.

import time,os
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium import webdriver

try:
    # STEP 1 - LOAD PAGE
    options = webdriver.ChromeOptions()
    options.add_argument("--start-maximized")
    chrome_browser = webdriver.Chrome(chrome_options=options)
    chrome_browser.get("https://huew.co")
    WebDriverWait(chrome_browser,10).until(EC.title_contains("Huew | Your Catalog of Shoppable Fashion Inspirations"))

    # STEP 2 - CLICK ON "YOU"
    you_button = chrome_browser.find_element_by_xpath('//div[@class="desktop-menu-icon-text" and text()="YOU"]')
    time.sleep(2)
    you_button.click()

    # STEP 3 - CLICK ON "LOGIN USING GOOGLE"
    google_login_button = chrome_browser.find_element_by_xpath('//img[@class="social-login-button" and @ng-click="login(\'google\')"]')
    google_login_button.click()

    # STEP 4 - READ USERNAME AND PASSWORD FOR THE GOOGLE ACCOUNT
    with open("credentials.txt", "r") as f:
        lines = f.readlines()
        for line in lines:
            username, password = line.split(":")

    # STEP 5 - SWITCH TO THE NEW WINDOW
    window_handles = chrome_browser.window_handles
    parent_handle = chrome_browser.current_window_handle
    for window_handle in window_handles:
        if window_handle != parent_handle:
            chrome_browser.switch_to.window(window_handle)
            break

    # STEP 6 - TYPE IN USERNAME AND PASSWORD
    input_field = WebDriverWait(chrome_browser, 5).until(EC.visibility_of_element_located((By.ID, "identifierId")))
    input_field.send_keys(username)
    next_button = chrome_browser.find_element_by_xpath('//span[text()="Next"]')
    next_button.click()

    input_field = WebDriverWait(chrome_browser, 5).until(EC.visibility_of_element_located((By.NAME, "password")))
    input_field.send_keys(password)
    next_button = chrome_browser.find_element_by_xpath('//span[text()="Next"]')
    next_button.click()
    time.sleep(5)

    # STEP 7 - SWITCH BACK TO THE OLD WINDOW AND CLICK "DISCOVER"
    chrome_browser.switch_to.window(parent_handle)
    discover_button = chrome_browser.find_element_by_xpath('//div[@class="desktop-menu-icon-text" and text()="DISCOVER"]')
    discover_button.click()

    # STEP 8 - UPLOAD THE PHOTO AND CLICK ON "SUBMIT"
    file_upload_panel = WebDriverWait(chrome_browser, 60).until(lambda chrome_browser: chrome_browser.find_element_by_xpath('//input[@type="file"]'))
    file_upload_panel.send_keys(os.getcwd()+"\\fashion_pic.jpg")
    submit_button = WebDriverWait(chrome_browser, 5).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "button.desktop-photo-submit.ng-scope")))
    chrome_browser.execute_script('''document.querySelector('button.desktop-photo-submit.ng-scope').click()''')

    # STEP 9 - WAIT FOR THE "SAVE" BUTTON TO APPEAR AND CLICK ON IT
    save_button = WebDriverWait(chrome_browser, 60).until(EC.element_to_be_clickable((By.XPATH, '//button[text()="SAVE"]')))
    save_button.click()
    time.sleep(5)

    # STEP 10 - CLICK ON "HERE" LINK
    here_link = chrome_browser.find_element_by_xpath('//a[text()="here"]')
    here_link.click()

except ValueError:
    print("Please ensure that the input file has the username and password saved in the format specified in readme.txt")


texts:
I wrote some code that reads the output of the rcon users command on the CS 1.6 console. It then notifies me of any players that are not in my whitelist.csv or are in my blacklist. The program requires 3 files as inputs:

A text file containing the raw output of the rcon users command on CS 1.6 console.
A CSV file containing the SteamID and name of the white-listed players.
A CSV file containing the SteamID and name of the black-listed players.

#!/usr/bin/env python3
import csv
import re

class WhiteListVerifier:
    """
    Class to check if non-white-listed players are playing CS.
    """
    def __init__(self, users_filepath, whitelist_filepath, blacklist_filepath):
        """
        Get filepaths and load the following files: users file , whitelist file and blacklist file

        users_filepath: Path to a text file which contains the raw output of the 'rcon users' in the in-game console.
        whitelist_filepath: Path to a csv file which contains Steam IDs and player-names of the white-listed players.
        blacklist_filepath: Path to a csv file which contains Steam IDs, player-names and alert-message for the black-listed players.
        """
        with open(users_filepath) as f:
            self.users_rawcontents = f.read()
        self.whitelist = list(csv.DictReader(open(whitelist_filepath)))
        self.blacklist = list(csv.DictReader(open(blacklist_filepath)))

    def get_playername(self, steamid, player_records):
        """
        Function to return name of a person if steamid exits in given records
        and return 'Unknown' otherwise.
        """
        for player in player_records:
            if steamid == player['Steam_ID']:
                return player['Player_Name']
        return 'Unknown'

    def get_active_users_steamids(self):
        """
        Function to extract the Steam IDs using output of 'rcon users' command.
        """
        active_users_steamids = re.findall(r'STEAM_[0-5]:[01]:\d+', self.users_rawcontents)
        return active_users_steamids

    def verify_steamids(self):
        """
        Function to alert if people other than the ones mentioned in the whitelist are playing.
        """
        active_users_steamids = self.get_active_users_steamids()
        num_nonwhitelisted_users = 0

        for active_user in active_users_steamids:
            player = self.get_playername(active_user, self.whitelist)
            if player is 'Unknown':
                num_nonwhitelisted_users += 1
                nonwhitelisted_playername = self.get_playername(active_user, self.blacklist)
                print('-- nonwhitelisted player: '+str(nonwhitelisted_playername))
        print('>> Total number of non-whitelisted players: '+str(num_nonwhitelisted_users))

if __name__ == '__main__':
    checker = WhiteListVerifier('data/users.txt', 'data/whitelist.csv', 'data/blacklist.csv')
    checker.verify_steamids()


texts:
I want to create a shopping cart project with discounts for products. For instance, if you buy 2 books, you can get 10% off Parker pens. I created a shopping cart example, but without exception handling in this version.

Are my classes Product, Basket, Offers and Discounts properly structured, or what changes do I need to make to make it right? To calculate discounts, should I iterate my basket or iterate the list of offers? The offers are a little tricky as mentioned at the top.

Product

public class Product {

    private String name;
    private int price;

...with get methods + hashcode and equals.

Basket

public class Basket {

    Map<Product, Integer> items;

    public Basket() {
        items = new HashMap<>();
    }

    public Map<Product, Integer> getItems() {
        return items;
    }

    public void addProduct(Product product){
        if(items.containsKey(product)){
            items.compute(product, (p,q ) -> Integer.valueOf(q+1));
        }else{
            items.put(product, 1);
        }
    }

    public void removeProduct(Product product){
        if(items.get(product).intValue() > 1){
            items.compute(product, (p, q) -> Integer.valueOf(q-1));
        }else{
            items.remove(product);
        }
    }
}

Discount

public class Discount {

    private Product product;
    private int discountPercent ;

    public Product getProduct() {
        return product;
    }

    public int getDiscountPercent() {
        return discountPercent;
    }

    public Discount(Product product, int discountPercent) {
        super();
        this.product = product;
        this.discountPercent = discountPercent;
    }

    @Override
    public String toString() {
        return "Discount [product=" + product + ", discountPercent=" + discountPercent + "]";
    }
}

Offer

public class Offer {

    private Product product;
    private int quantity;
    private Discount discount;

    public Product getProduct() {
        return product;
    }
    public void setProduct(Product product) {
        this.product = product;
    }

    public int getQuantity() {
        return quantity;
    }
    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
    public Discount getDiscount() {
        return discount;
    }
    public void setDiscount(Discount discount) {
        this.discount = discount;
    }

    public Offer(Product product, int quantity, Discount discount) {
        super();
        this.product = product;
        this.quantity = quantity;
        this.discount = discount;
    }
    @Override
    public String toString() {
        return "Offer [product=" + product + ", quantity=" + quantity + ", discount=" + discount + "]";
    }

}


texts:
I want to have fast cache in which I want to keep all my nomenclature data.
I don't want to go with Memcached because I have to do serialize/de-serialize on each object which is slow.

So I choose to be less effective in memory and keep the cache in each server instance.
I am sure I am doing it in the wrong way because the NoCache module - which skips my cache and hits the Rails cache is faster than mine.

Here is how it is initialized

$cache = Cache.new

Here is the example usage

property_types = $cache['PropertyType']

and here is the source

module DirectCache
  def init_cache
  end

  def reload_model(model_class)
    key = get_key(model_class)
    klass = key.constantize
    object = klass.scoped
    puts "Loading cache for #{key}..."
    if klass.respond_to?(:translates) and klass.translates?
      puts "  Adding translation in the model for #{klass}"
      object = object.includes(:translations)
      self.storage[key] = object.send("all")
    end
  end

  def [] class_name_or_object
    puts "Hiting cache for #{class_name_or_object}"
    key = get_key(class_name_or_object)
    reload_model(class_name_or_object) if self.storage[key].blank? or self.storage[key].empty?
    raise "#{key} is missing in the cache #{@cache.keys.join ', '}" unless key? key
    self.storage[key]
  end

  def init_cache
  end

end

module NoCache
  def reload_model(model_class)
    key = get_key(model_class)
    self.storage[key] = key.constantize
  end

  def [] class_name_or_object
    key = get_key(class_name_or_object)
    raise "#{key} is missing in the cache #{@cache.keys.join ', '}" unless key? key
    klass = self.storage[key]
    object = klass.scoped
    if klass.respond_to?(:translates) and klass.translates?
      puts "Adding translation in the model for #{klass}"
      object = object.includes(:translations)
    end
    object.send("all")
  end

  def init_cache
  end

end

class Cache
  include DirectCache
  #  include NoCache
  #  include OpenStructCache

  @@models = [
    PropertyFunction,
    PropertyCategoryLocation,
    ConstructionType,
 ....20 more ....
    ExposureType,
  ]

  cattr_reader :models

  def initialize
    @cache = {}
    begin
      init_cache
    rescue
      puts "missing tables"
    end
  end

  def storage
    @cache
  end

  # returns the the key - aways string
  def get_key class_name_or_record
    case class_name_or_record
    when Class
      key = class_name_or_record.to_s
    when String
      key = class_name_or_record
    else
      key = class_name_or_record.class.to_s
    end
    key
  end

  def key? class_name_or_object
    key = get_key(class_name_or_object)
    self.storage.keys.include? key
  end

end


texts: getting inferences working with typescript pubsubber

texts:
So I'm learning typescript and I'm making a simple functional PubSub system. I want the user to be able to define topics and the data for those topics. So far I've got the below code, but I really want to improve it.
I'm not sure if I can get rid of the unknown in <T extends Record<string,unknown>>. I don't think that's a huge issue for me. I'd really like to get rid of the Set<Subscriber> part of the map that holds the subscribers. I tried something simple like Set<Subscriber<T[keyof T]>> but then it complains below where I am using <R extends keyof T>. Maybe that's the part that needs fixing?
Any and all suggestions welcome of course!
type Subscriber<R> = (data: R) => void;

const pubSubber = <T extends Record<string, unknown>>() => {
  const subscribers = new Map<keyof T, Set<Subscriber<any>>>();
  return {
    subscribe: <R extends keyof T>(topic: R, subscriber: Subscriber<T[R]>) => {
      const current = (subscribers.get(topic) || new Set()) as Set<
        Subscriber<T[R]>
      >;
      current.add(subscriber);
      subscribers.set(topic, current);
      return () => current.delete(subscriber);
    },
    publish: <R extends keyof T>(topic: R, data: T[R]) => {
      const toCall = Array.from((subscribers.get(topic) || [])) as Subscriber<T[R]>[];
      toCall.map((f) => f(data));
    },
  };
};

type Topics = {
  gear_with_radius: {
    center: number;
    radius: number;
  };
  outside: {
    help: boolean;
  };
};
const myPubSubber = pubSubber<Topics>();
myPubSubber.publish('gear_with_radius', { center: 10, radius: 5 });


texts: Changing button colors based on user input

texts:
I am using C# to get the user's input of how many buttons to change the color of.  The buttons are in rows that have 1-10 button in each.  If the user enters 11, then the entire first row will be filled out and the first button on the second row will change color.  I have figured out how to accommodate for different numbers the user might enter, but hoping to get some advice on how to code better without using a large if, if else, statement.

internal void ChangeTileColor(ConnectorData connectorData, int j)
{
    int row = 0;
    if (j < 10)
    {

    }
    else if (j < 20)
    {
        j -= 10;
        row++;
    }
    else if (j < 30)
    {
        j -= 20;
        row += 2;
    }
    else if (j < 40)
    {
        j -= 30;
        row += 3;
    }
    else if (j < 50)
    {
        j -= 40;
        row += 4;
    }
    else if (j < 60)
    {
        j -= 50;
        row += 5;
    }
    Button button = this.tableLayoutPanel1.GetControlFromPosition(j, row) as Button;
    button.BackColor = Color.Lime;
}


texts:
I have been using Python 3 to learn programming, and this is a very basic task, but I want to gain good programming patterns/habits at the very beginning.

The program will first randomly generate a number unknown to the user. The user needs to guess what that number is. The program interacts with the user.

import random
randomNumber = random.randrange(0,100)
print("Random number has been generated")
guessed = False
while guessed==False:
    userInput = int(input("Your guess pleas: "))
    if userInput==randomNumber:
        guessed = True
        print("Well done!")
    elif userInput>100:
        print("Our guess range is between 0 and 100, please try a bit lower")
    elif userInput<0:
        print("Our guess range is between 0 and 100, please try a bit higher")
    elif userInput>randomNumber:
        print("Try one more time, a bit lower")
    elif userInput < randomNumber:
        print("Try one more time, a bit higher")

print("End of program")


texts:
I'd appreciate any and all criticism about this code.  I didn't have a particular use case in mind when I wrote it; I just wanted to try implementing linked lists.  My comments are not very useful, I think.  I'm not a very experienced programmer, so there's probably plenty of things I could improve or fix here.

Here is the header file:

// llist.h
#ifndef LLIST_H_
#define LLIST_H_

struct LList;
typedef struct LList LList;

struct LLNode;
typedef struct LLNode LLNode;

struct LList {
    LLNode *front, *back;
};

struct LLNode {
    void *data;
    LLNode *next;
};

LList* llist_new(LList **self);
void llist_add(LList *self, void *v);
void llist_remove(LList *self, LLNode *node);
void llist_insert(LLNode *node, void *v);
void llist_destroy(LList *self);

#endif

Here is the .c file:

// llist.c
#include <assert.h>
#include <stdlib.h>

#include "llist.h"

// Initialize a new, empty LList, in dynamically allocated memory.
LList *llist_new(LList **self) {
    *self = malloc(sizeof (LList));
    if (self == NULL) { return NULL; }

    (*self)->front = NULL;
    (*self)->back = NULL;

    return *self;
}

// Append a value to the LList.  Creates a new node.
void llist_add(LList *self, void *v) {
    LLNode *node = malloc(sizeof (LLNode));
    assert(node != NULL);

    node->data = v;
    node->next = NULL;

    // Put this node at the back of the list.
    if (self->front != NULL) {
        self->back->next = node;
        self->back = node;
    } else {
        self->back = node;
        self->front = node;
    }
}

// Iterate over the LList to locate a node, and then remove it from the list.
void llist_remove(LList *self, LLNode *node) {
    LLNode *iter_node = self->front;
    LLNode *prev_node = NULL;

    while (iter_node != NULL) {
        if (iter_node == node) {
            if (prev_node != NULL) { prev_node->next = iter_node->next; }
            else { self->front = NULL; }
            free(iter_node);
            return;
        }
        prev_node = iter_node;
        iter_node = iter_node->next;
    }

}

// Insert a value after a particular node.
void llist_insert(LLNode *node, void *v) {
    LLNode *next = node->next;
    LLNode *new_node = malloc(sizeof (LLNode));

    new_node->data = v;
    new_node->next = next;

    node->next = new_node;
}

void llist_destroy(LList *self) {
    LLNode *iter_node = self->front;

    while (iter_node != NULL) {
        LLNode *next = iter_node->next;
        free(iter_node);
        iter_node = next;
    }

    free(self);
}


texts:
protected static String[] applyInterleave(String interleave, int lengthOfSequence, int numOfPermutations){
    String[] interleavedPatterns = new String[numOfPermutations];
    char[] pattern = interleave.toCharArray();
    StringBuilder interleavedPattern = new StringBuilder("");

    for(int i = 0; i < numOfPermutations; i++){
        char[] data = designs[i].toCharArray();
        for(int j = 0; j < lengthOfSequence; j++)
            interleavedPattern.append(data[Character.getNumericValue(pattern[j])-1]);

        interleavedPatterns[i] = interleavedPattern.toString();
        interleavedPattern = new StringBuilder("");
    }
    return interleavedPatterns;
}

In this code, design is of size numOfPermutations and each element in design is a string of length lengthOfSequence. Now, I am taking each element in design and applying an interleave mapping based on the parameter interleave.

For instance, let's say the string is 1432. Then, I take each element in design and I reorder it so that the 1st char of string is still the 1st, then the 4th char becomes the 2nd, the 3rd char stays the 3rd, and the 2nd char becomes the 4th.

For example, if the first element in design, design[0] = 4321 and if the passed in parameter for interleave is 1432 then 4321 is reordered as 4123. There are very specific reasons why I am only working with String instead of int, so I am not interested in changing the variable types.

Now, if my design array is really large, say 362880 indices long, then this method takes quite a while. I have optimized to the best of my ability, but is there a way to speed this up even more?


texts: Pad a ragged multidimensional array to rectangular shape

texts:
For some machine learning purpose, I need to work with sequences with different lengths. To be able to process efficiently those sequences, I need to process them in batches of size size_batch. A batch typically has 4 dimensions and I want to convert it to a numpy's ndarray with 4 dimensions. For each sequence, I need to pad with some defined pad_value such that each element has the same size: the maximal size.

For example, with 3 dimensional input:

[[[0, 1, 2],
  [3],
  [4, 5]],
 [[6]],
 [[7, 8],
  [9]]]

desired output for pad_value -1 is:

[[[0, 1, 2],
  [3, -1, -1],
  [4, 5, -1]],
 [[6, -1, -1],
  [-1, -1, -1],
  [-1, -1, -1]]
 [[7, 8, -1],
  [9, -1, -1],
  [-1, -1, -1]]]

which has shape (3, 3, 3).
For this problem, one can assume that there are no empty lists in the input.
Here is the solution I came up with:

import numpy as np
import itertools as it
from typing import List

def pad(array: List, pad_value: np.int32, dtype: type = np.int32) -> np.ndarray:
    """ Pads a nested list to the max shape and fill empty values with pad_value

    :param array: high dimensional list to be padded
    :param pad_value: value appended to
    :param dtype: type of the output
    :return: padded copy of param array
    """
    # Get max shape
    def get_max_shape(arr, ax=0, dims=[]):
        try:
            if ax >= len(dims):
                dims.append(len(arr))
            else:
                dims[ax] = max(dims[ax], len(arr))

            for i in arr:
                get_max_shape(i, ax+1, dims)
        except TypeError:  # On non iterable / lengthless objects (leaves)
            pass

        return dims

    dims = get_max_shape(array)

    # Pad values
    def get_item(arr, idx):
        while True:
            i, *idx = idx
            arr = arr[i]
            if not idx:
                break
        return arr

    r = np.zeros(dims, dtype=dtype) + pad_value
    for idx in it.product(*map(range, dims)):
        # idx run though all possible tuple of indices that might
        # contain a value in array
        try:
            r[idx] = get_item(array, idx)
        except IndexError:
            continue

    return r

It does not feel really pythonic but does the job. Is there any better way to do it I should know ? I think I might be able to improve its speed by doing smart breaks in the last loop but I haven't dug much yet.


texts:
I've written a C function to find the program less that the operating system should provide. If lessis not provided, some other pager variable should be used. I compile it with gcc -ansi -pedantic -Wall -O3.

int findless(char *less_token, int ret) {
    int breakloop = 0;
    char *new_str;
    while (less_token != NULL) {
        if ((new_str = malloc(strlen(less_token) + strlen("/less") + 1)) != NULL) {
            new_str[0] = '\0';
            strcat(new_str, less_token);
            strcat(new_str, "/less");
            if (file_exist(new_str)) {
                /* Found less */
                ret = 0;
                breakloop = 1;
            }
            free(new_str);
            if (breakloop) {
                break;
            }
        } else {
            printf("malloc failed!\n");
        }
        less_token = strtok(NULL, ":");
    }
    return ret;
}

Can you please review it? I put in in a separate utilities util.c file and I'm including it with a util.h interface.


texts:
I am doing my research about scheduling by using Matlab. I am a new Matlab user and I have a problem with time execution of my following code:

clc
clear all
A=8;
B=12;
C=10;
ProcessTime= [ 11 11 11 11 4 4 4 4 4 4 4 2 ]; %Converting Matrice

RandomMatriceA=zeros(A,B,C);
RandomMatriceB=zeros(A,B,C);
SumRandomMatriceB=zeros(1,A,C);
ConvertMatriceA=zeros(A,B,C);
ProcessRandomMatriceA=zeros(A,B,C);
StartProcess=zeros(A,B,C);
EndProcess=zeros(A,B,C);
StartPost=zeros(A,B,C);

for ii=1:C;
    for x=1:2:A-1;
        %make first random matrice
        [vals RandomMatriceA(x,:,ii)]=sort(rand(1,B),2); %batasan tidak boleh satu kelompok melakukan lebih dari satu aktivitas dalam satu waktu
        done=false;
        while ~done,
              %make row of second random matrice
              NewRowRandomMatriceB=randi([0 2],1,B);
              %Make sure sum all element per row in RandomMatriceB <=11
              done=sum(NewRowRandomMatriceB)<12;
        end
        RandomMatriceB(x,:,ii)=NewRowRandomMatriceB;
        %After making RandomMatriceA and RandomMatriceB, then Make New
        %Matrice
        %To know varible of new matrice which is result of combining
        %RandomMatriceA,RandomMatriceB and ProcessTime
        for y=1:B,
            ConvertMatriceA(x,y,ii)=ProcessTime(RandomMatriceA(x,y,ii));%FirstVarible:Consecutive The Number of value in all element of RandomMatriceA
        end
        ProcessRandomMatriceA(x,:,ii)=ProcessTime(RandomMatriceA(x,:,ii))+RandomMatriceB(x,:,ii);
        EndProcess(x,:,ii)=cumsum(ProcessRandomMatriceA(x,:,ii),2);%secondVaribale:to know in which column The Consecutive value RandomMatrice will be end
        StartProcess(x,:,ii)=EndProcess(x,:,ii)-(ProcessTime(RandomMatriceA(x,:,ii))-1);%ThirdVariable:to know in which column The Consecutive Value will be start
        for yy=1:B;
            N=RandomMatriceA(x,yy,ii);
            StartPost(x,N,ii)=StartProcess(x,yy,ii);
        end
    end
    for h=2:2:A;
        doneA=false;
        while ~doneA,
          [vals RandomMatriceA(h,:,ii)]=sort(rand(1,B),2);
          doneB=false;
          while ~doneB,
                 NewRowRandomMatriceB=randi([0 2],1,B);
                 doneB= sum(NewRowRandomMatriceB)<12;
          end
          RandomMatriceB(h,:,ii)=NewRowRandomMatriceB;
          for y=1:B;
              ConvertMatriceA(h,y,ii)=ProcessTime(RandomMatriceA(h,y,ii));
          end
          ProcessRandomMatriceA(h,:,ii)=ProcessTime(RandomMatriceA(h,:,ii))+RandomMatriceB(h,:,ii);
          EndProcess(h,:,ii)=cumsum(ProcessRandomMatriceA(h,:,ii),2);%secondVaribale:to know in which column The Consecutive value RandomMatrice will be end
          StartProcess(h,:,ii)=EndProcess(h,:,ii)-(ProcessTime(RandomMatriceA(h,:,ii))-1);%ThirdVariable:to know in which column The Consecutive Value will be start
          for z=1:B;
            N=RandomMatriceA(h,z,ii);
            StartPost(h,N,ii)=StartProcess(h,z,ii);
          end
           doneA =all(ismember(StartPost(h,1:4,ii),StartPost(h-1,1:4,ii)));
        end
        %arrange value in column 1 until 4 in order that it will have same
        %value
        StartPost(h,1:4,ii)=StartPost(h-1,1:4,ii);
    end
end

After using the profile viewer, I know that my problem is in this following code. This part takes too much execution time.

....
end
           doneA =all(ismember(StartPost(h,1:4,ii),StartPost(h-1,1:4,ii)));
        end
        %arrange value in column 1 until 4 in order that it will have same
        %value
        StartPost(h,1:4,ii)=StartPost(h-1,1:4,ii);
    end

How can I improve it and make it run faster?


texts: Extracting contents of dictionary contained in Pandas dataframe to make new dataframe columns

texts:
I created a Pandas dataframe from a MongoDB query.

c = db.runs.find().limit(limit)
df = pd.DataFrame(list(c))

Right now one column of the dataframe corresponds to a document nested within the original MongoDB document, now typed as a dictionary. The dictionary is in the run_info column.

I would like to extract some of the dictionary's values to make new columns of the data frame. Is there a general way to do this? If not, what is the best brute force method specific to my data?

Here is my brute force approach, and it's horrendous. Even for a dataframe of only 200 rows, this is taking several minutes:

run_info = df['run_info']
# want to extra values from dictionary stored in column df['run_info']
# some values are within dictionaries nested within top dictionary
# these are 'author' and 'weather'
for i in range(len(df['run'])):
    g = run_info[i]
    if g.get('weather'):
        for name in weather_list:
            if g.get('weather').get(name):
                try:
                    df.set_value(i, name, g['weather'][name])
                except:
                    pass
    if g.get('author'):
        for name in author_list:
            if g.get('author').get(name):
                try:
                    df.set_value(i, name, g['author'][name])
                except:
                    pass
    for name in name_list:
        if g.get(name):
            try:
                if name is 'local_start_time':
                    df.set_value(i, name, g[name][0:19])
                else:
                    df.set_value(i, name, g[name])
            except:
                pass

I'd appreciate any and all suggestions for how to improve the speed here. Also I am using the try...except because once in a while the encoding on some funky character is causing a ValueError.


texts:
This code is the basic structure I use for coding plugins. It's pretty standard with the settings extended and the each loop.  However, now I'm working on the best way to provide setters/getters. For example, I may want to do something like:

var sp = $("#container").wScratchPad();

alert(sp.wScratchPad('size'));

sp.wScratchPad('color', '#FF0000');
sp.wScratchPad('reset');

I have my little setters/getters area below and this is what I have come up with so far. I'm looking for a nice clean standard way to do this for all future plugins, something I can just copy and paste for the most part at least. I'm looking for any input on this, particularly if there are anyways to do it cleaner and with less code.

(function($)
{
    var defaultSettings =
    {
        //settings here
    };

    $.fn.wScratchPad = function(option, settings)
    {
        //check for setter/getters
        if(typeof option === 'object')
        {
            settings = option;
        }
        else if(typeof option == 'string')
        {
            var sp = this.data('_wScratchPad');
            var hit = true;

            if(sp)
            {
                if(option == 'reset') sp.reset();
                else if(defaultSettings[option])
                {
                    if(settings) sp.settings[option] = settings;
                    else return sp.settings[option];
                }
                else hit = false;
            }
            else hit = false;

            return hit;
        }

        settings = $.extend({}, defaultSettings, settings || {});

        return this.each(function()
        {
            var elem = $(this);

            var sp = new ScratchPad(settings);

            //code here

            elem.data('wScratchPad', sp);
        });
    }

    //clasess/prototypes here
})(jQuery);


texts: Script that helps people make better choices

texts:
This is a "Help me make a choice" script where the user can input two options and then, based on the (3) reasons why they are good options, and the reasons weight the script will tell you which option you should choose.

This is my first Python script based on an idea I had and I'd like to know how I could make it better. For example, should I store the reasons (ie. option1a) in a list, dictionary or keep them in variables? Should I do the same to the weight (ie. option1aw) of each option?

The code works and does what I wanted it to do, but I don't know if I did in the best way possible.

import random

print("First, tell me what your options are.")

option1 = input("Option 1: ")
option2 = input("Ok. Now tell me the other option: ")

option1a = input("\nGood. Now tell me a reason why \'{}\' is a good choice: ".format(option1))

option1b = input("Ok. Now tell me another reason why \'{}\' is a good choice: ".format(option1))

option1c = input("Ok. Now tell me another reason why \'{}\' is a good choice: ".format(option1))

option2a = input("\nThats all for \'{}\'. Now tell me why \'{}\' is a good choice: ".format(option1, option2))

option2b = input("Now tell me another reason why \'{}\' is a good choice: ".format(option2))

option2c = input("Now tell me another reason why \'{}\' is a good choice: ".format(option2))

option1aw = int(input("\nNow let's evaluate the options. Regarding \'{}\', "
                      "from 1 to 5, tell me how important is \'{}\'? ".format(option1, option1a)))

option1bw = int(input("Still regarding \'{}\', from 1 to 5, tell me how important is \'{}\'? ".format(option1, option1b)))

option1cw = int(input("How about \'{}\', from 1 to 5, tell me how important it is: ".format(option1c)))

option2aw = int(input("\nNow let's evaluate the rest of the options. Regarding \'{}\',"
                      " from 1 to 5, tell me how important is \'{}\'? ".format(option2, option2a)))

option2bw = int(input("Still regarding \'{}\', from 1 to 5, tell me how important is \'{}\'? ".format(option2, option2b)))

option2cw = int(input("How about \'{}\', from 1 to 5, tell me how important it is: ".format(option2c)))

prompt = input("\nWe'll calculate now. Click enter when you are ready to see the results. > ")

option1result = option1aw + option1bw + option1cw

option2result = option2aw + option2bw + option2cw

options = [option1, option2]

def coinflip():
    print("Your best choice is:")
    print(options[random.randint(0, len(options)-1)])

if option1result > option2result:
    print("\n\'{}\' is your best choice based on the reasons you gave me. ".format(option1))

elif option1result == option2result:
    print("\nHonestly, both are good options. Do you want to flip a coin? Press enter. ")
    input()
    coinflip()

else:
    print("\n\'{}\' is your best choice based on the reasons you gave me. ".format(option2))

quit()


texts: Using os.scandir to get all txt files in subfolders

texts:
I have a parent dir that has X children dirs each with Y txt files. I want to list all txt files. Is there a way to simplify this?

for entry in os.scandir(DIR):
        for subentry in os.scandir(entry.path):
            if subentry.is_dir():
                for file in os.scandir(subentry.path):
                    if file.is_file() and file.name.endswith("txt"):
                        print(file.name)


texts:
Here is a simple app that i am trying to implement in java.
my goal is to write a program that can convert ASCII to Binary and back.

Questions:

Am i violating any OOP Rule.
Is my code readable ?
How can i make it more efficient ?
Anything that want to suggest.

Code:

public class FXMLDocumentController implements Initializable {

@FXML
TextArea asciiTextArea;
@FXML
TextArea binaryTextArea;
@FXML
StackPane animationPane;
private static final int AMOUNT_OF_BITS = 8;

@FXML
private void handleBinaryToText(ActionEvent event) {
    Callable<String> task = () -> binaryToAscii(binaryTextArea.getText());
    try {
        runTask(task, asciiTextArea);
    } catch (InterruptedException | ExecutionException ex) {
        asciiTextArea.setText(ex.toString());
    }

}

@FXML
private void handleTextToBinary(ActionEvent event) {
    Callable<String> task = () -> asciiToBinary(asciiTextArea.getText());
    try {
        runTask(task, binaryTextArea);
    } catch (InterruptedException | ExecutionException ex) {
        binaryTextArea.setText(ex.toString());
    }
}

@Override
public void initialize(URL location, ResourceBundle resources) {
    //Validate the Binary TextArea
    final Pattern binaryRegex = Pattern.compile("\\A[01\\n]*\\Z");
    Predicate<String> tester = binaryRegex.asPredicate();
    binaryTextArea.setTextFormatter(new TextFormatter<>(change -> {
        if (!tester.test(change.getControlNewText())) {
            return null;
        }
        return change;
    }));
       //binaryTextArea.setTextFormatter();

}

// Create the Binary To Text Task task
private String binaryToAscii(final String input) {

    if (input.length() % AMOUNT_OF_BITS != 0) {
        String msg = "Input must be a multiple of " + AMOUNT_OF_BITS;
        binaryTextArea.setText(msg);
        throw new IllegalArgumentException(msg);
    }
    final int INPUT_LEN = input.length();
    final int BUILDER_SIZE = INPUT_LEN / 8;
    StringBuilder result = new StringBuilder(BUILDER_SIZE);

    for (int i = 0; i < INPUT_LEN; i += AMOUNT_OF_BITS) {
        char charCode = (char) Integer.parseInt(input.substring(i, i + AMOUNT_OF_BITS), 2);
        result.append(charCode);
    }
    return result.toString();
}

// Create the Binary To Text Task
private String asciiToBinary(String text) {
    final byte[] bytes = text.getBytes();
    StringBuilder result = new StringBuilder(bytes.length * 8);
    for (byte b : bytes) {
        int val = b;
        for (int i = 0; i < AMOUNT_OF_BITS; i++) {
            result.append((val & 128) == 0 ? 0 : 1);
            val <<= 1;
        }
    }
    return result.toString();
}

private void runTask(Callable<String> task, TextArea textArea) throws InterruptedException, ExecutionException {
    ExecutorService thread = Executors.newFixedThreadPool(1);
    final String result = thread.submit(task).get();
    Platform.runLater(() -> {
        textArea.setText(result);
    });
    thread.shutdown();
}

}

Github link


texts: Detecting which properties have been changed from two objects

texts:
I have the following code. Providing two objects cmd and this.xxx.properties, script detects the only property changed and mutate the input object (cmd).

Script works fine but I would like to know if I could optimize or improve my code for speed.

    _deltaProperties: function (cmd) {

        var dataBefore = this.xxx.properties,
            newData = {};
        for (var prop in cmd.properties) {
            var newValue = cmd.properties[prop],
                oldValue = dataBefore[prop];
            if (newValue !== oldValue) {
                newData[prop] = cmd.properties[prop];
            }
        }
        cmd.properties = newData;
        return cmd;
    },


texts:
When I am scraping from a web page I need a way to open and read it. Previously, I used two functions, one for requests and one for Selenium

def read_page_w_requests(url):
    try:
        headers = {'User-agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) \
                    Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1'}
        r = requests.get(url, headers=headers)
        text = r.text
    except Exception, e:
        print "Read page with requests error:", e
        text = None
    return text

def read_page_w_selenium(driver, url, element_be_located=""):
    try:
        driver.get(url)
        wait = WebDriverWait(driver, 10)
        if element_be_located:
            wait.until(EC.visibility_of_element_located((By.ID, element_be_located)))
            text = driver.page_source
        else:
            text = driver.page_source

    except Exception, e:
        print "Read page error:", e
        text = None

    return text

I am thinking of using just one, that combines both:

import requests
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

def get_driver():
    try:
        dcap = dict(DesiredCapabilities.PHANTOMJS)
        dcap["phantomjs.page.settings.userAgent"] = (
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/53 "
            "(KHTML, like Gecko) Chrome/15.0.87"
        )
        driver = webdriver.PhantomJS(desired_capabilities=dcap)
        return driver
    except Exception, e:
        print "Driver error:", e
        return None

def get_page_source(url, driver="", element=""):
    if driver:
        try:
            driver.get(url)
            wait = WebDriverWait(driver, 10)
            if element:
                wait.until(EC.visibility_of_element_located((By.ID, element)))
            text = driver.page_source
        except Exception, e:
            print "Read page error:", e
            text = None

    else:
        try:
            headers = {'User-agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) \
                        Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1'}
            r = requests.get(url, headers=headers)
            text = r.text
        except Exception, e:
            print "Read page error:", e
            text = None

    return text

Is it a good idea to combine two functions that do the same thing with a different way in a single function? One of my concerns is the name of each function.


texts:
I've seen a number of questions on Stack Overflow of the kind of "How do I sort on fields X AND Y?" The most common answers to those questions consists of "Write a custom Comparator."

But what if you have 3 fields you can sort on? Or 13? or 300? My solution is this utility class, so that rather than writing a billion different Comparators for every possible combination you might want, you write just 3 (or 13, etc.) simple ones and essentially composite them to get the desired behavior.

This method is designed to be used as essentially an expanded version of Collections.sort(List list, Comparator c) so I want to adhere to the same contract as much as possible.

I am also interested in ways to improve the documentation/API and finding possibly troublesome corner cases.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * A utility class for sorting a list using multiple sorting criteria.
 *
 */
public class Multisorter {
    /**
     * Sorts the given List using the given Comparators.
     *
     * The List is sorted by the Comparators in the order the Comparators are
     * given; the elements are sorted according to the first Comparator, then
     * all of the elements that are considered "equal" are subsorted recursively
     * by the next Comparator and so on.
     *
     * This method makes use of Collections.sort(List<T>, Comparator<T>)
     * internally and obeys the same contract.
     *
     * @param <T>
     *            the generic type of the list.
     *
     * @param list
     *            the List to sort
     * @param comparators
     *            the comparators to sort with
     * @return the sorted List
     */
    public static <T> void sort(List<T> list, Comparator<? super T>... comparators) {
        if (comparators.length <= 0) {
            throw new IllegalArgumentException("Must provide at least one Comparator to sort with.");
        }
        Collections.sort(list, comparators[0]);
        if (comparators.length > 1) {
            List<List<T>> subCollections = new ArrayList<>();
            for (T element : list) {
                boolean matchFound = false;
                for (List<T> subList : subCollections) {
                    if (comparators[0].compare(element, subList.get(0)) == 0) {
                        subList.add(element);
                        matchFound = true;
                    }
                    if (matchFound) {
                        break;
                    }
                }
                if (!matchFound) {
                    int lastIndex = subCollections.size();
                    subCollections.add(lastIndex, new ArrayList<>());
                    subCollections.get(lastIndex).add(element);
                }
            }

            // Sort each of the subcollections recursively without the first Comparator
            for (List<T> subList : subCollections) {
                sort(subList, Arrays.copyOfRange(comparators, 1, comparators.length));
            }
            // Aggregate all the subcollections
            list.clear();
            for (List<T> subList : subCollections) {
                list.addAll(subList);
            }
        }
    }
}

However, based on comments by Alnitak and rolfl, I would just use the new thenComparing method in Comparator added in Java 8 that I didn't know about.


texts: Separation of code into functions and use of patern matching in Haskell

texts:
In the following:

import Data.Bits (popCount, shiftL, (.|.))
import Data.Char (chr, ord)
import Data.Word (Word8)
import qualified Data.ByteString as B

data MByteSequence = MByteSequence [Word8] -- a sequence of map bytes (len 0-15)

data Atom = TerminationAtom |
            NonOffsetAtom { nonOffsetGapLength :: Integer -- the number of gap bytes (max 2**53-1)
                          , nonOffsetGapValue :: Bool -- the value of the gap bytes
                          , followingMapBytes :: MByteSequence -- a sequence of following map bytes (len 1-15)
                          } |
            OffsetAtom { offsetGapLength :: Integer -- the number of gap bytes (max 2**53-1)
                       , offsetGapValue :: Bool -- the value of the gap bytes and the majority of the offset byte
                       , offsetBit :: Int -- the bit with a different value in the offset byte (0-7)
                       }

getAtomType :: Atom -> Int
getAtomType TerminationAtom = 1
getAtomType (NonOffsetAtom len _ _)
  | len <= 3 = fromInteger len
  | len > 3  = 4
getAtomType (OffsetAtom len val _)
  | len <= 3 && val == False = 5
  | len > 3                  = 6
  | len <= 3 && val == True  = 7

getFillField :: Atom -> Int
getFillField TerminationAtom = 0
getFillField (NonOffsetAtom _ val _) = if val then 1 else 0
getFillField (OffsetAtom len val _) = if len > 3 then (if val then 1 else 0) else fromInteger len

getDataField :: Atom -> Int
getDataField TerminationAtom = 0
getDataField (NonOffsetAtom _ val (MByteSequence mbytes))
  | length mbytes == 1 &&
    head mbytes == (if val then 0 else 0xFF) = 0
  | otherwise                                = length mbytes
getDataField (OffsetAtom _ _ bit) = bit

serialize :: Atom -> Word8
serialize TerminationAtom = 0
serialize (NonOffsetAtom x y z) = fromIntegral $ (getAtomType all) `shiftL` 6 .|.
                                                 (getFillField all) `shiftL` 4 .|.
                                                 (getDataField all)
  where all = NonOffsetAtom x y z
serialize (OffsetAtom x y z) = fromIntegral $ (getAtomType all) `shiftL` 6 .|.
                                              (getFillField all) `shiftL` 3 .|.
                                              (getDataField all)
  where all = OffsetAtom x y z

To me, serialize especially seems pretty ugly; the use of the where clauses and the similarity of the latter two pattern match cases all seems bad to me, yet I'm unsure what should be done instead. The other functions, while split up into logical blocks, seem perhaps too small? Should I use Word8 as the return type of all the functions (the return values are all small enough to fit)?

I'd welcome any feedback on code style, Haskell best practices (in general!), and any design patterns I should be using here!


texts:
I have a link (avatar)#qam-account-toggle and div.qam-account-items, the div containing user account links. I am toggling div on avatar click as well as click anywhere but div.qam-account-items

Here is my code. How can I optimize this better?

$('#qam-account-toggle').click(function(e){
    e.stopPropagation();
    $(this).toggleClass('account-active');
    $('.qam-account-items').fadeToggle('fast');
});

$(document).click(function(){
    $('#qam-account-toggle.account-active').removeClass('account-active');
    $('.qam-account-items:visible').hide();
});

$('.qam-account-items').click(function(event){
   event.stopPropagation();
});


texts:
I'm not quite sure I understood thread-safe correctly. I built the following registry:

@Service
public final class EntityDefinitionRegistry {

    private static final Logger logger = LogManager.getLogger(EntityDefinitionRegistry.class);

    private final HashMap<String, EntityDefinition> definitions = new HashMap<>();

    @Autowired
    public EntityDefinitionRegistry() {
        Set<EntityDefinition> definitions = EntityDefinitionWrapperLoader.getDefinitions();
    }

    public @NotNull EntityDefinition getDefinition(@NotNull String entityName) {
        if (StringUtils.isBlank(entityName)) {
            throw new InternalErrorException();
        }

        EntityDefinition definition = definitions.get(entityName);
        if (definition == null) {
            throw new InternalErrorException();
        }
        return definition;
    }
}

This is initialized in the constructor and never changed again. The same is true for the contained objects. Their fields never change.

public final class EntityDefinition {

    private static final Logger logger = LogManager.getLogger(EntityDefinition.class);

    @NonNull
    private final String name;

    @NotNull
    private final String packageName;

    private final boolean cached;

    private final boolean abstraction;

    private final InheritanceStrategy inheritanceStrategy;

    @Setter(AccessLevel.PACKAGE)
    private EntityDefinition superEntity;

    private final CopyOnWriteArraySet<EntityDefinition> subEntities = new CopyOnWriteArraySet<>();

    private final CopyOnWriteArraySet<EntityField> entityFields;

    private final CopyOnWriteArraySet<EntityField> dtoFields;

    private final CopyOnWriteArraySet<EntityRelationField> relationFields;

Have I understood correctly that the final specification and therefore only read accesses are always thread-safe?

I'm using Java 13.


texts: Compute the outputs of a generator in parallel

texts:
I am processing an unknown "length" of  generator object.
I have to keep things "lazy" because of memory management.
The processing is compute heavy, so writing it multiproc style is the solution (or at least it seems for me).
I have solved this problem of multiproc on generator object with a combination of monkey patch and a bounded Queue.
What really itches me is the monkey patch...
Do you think this is fine to apply imap() on a generator object? How would you do this?
I would like to underline that the focus is to compute the outputs of a generator in parallel.
From the perspective of this "minimal example" :
process_line, process_line_init, process_first_n_line

are the functions I am most interested about your opinion.
import multiprocessing as mp
import psutil
import queue
from typing import Any, Dict, Iterable, Set

def yield_n_line(n: int)-> Iterable[Dict[str, str]]:
    for i in range(n):
        yield {'body': "Never try to 'put' without a timeout sec declared"}

def get_unique_words(x: Dict[str, str])-> Set[str]:
    return set(x['body'].split())

def process_line(x:Dict[str, str])-> Set[str]:
    try:
        process_line.q.put(x, block=True, timeout=2)
    except queue.Full:
        pass
    return get_unique_words(x)

def process_line_init(q: mp.Queue)-> None:
    process_line.q = q

def process_first_n_line(number_of_lines: int)-> Any:
    n_line = yield_n_line(number_of_lines)

    if psutil.cpu_count(logical=False) > 4:
        cpu_count = psutil.cpu_count(logical=False)-2
    else:
        cpu_count = psutil.cpu_count(logical=False)
    q = mp.Queue(maxsize=8000)
    p = mp.Pool(cpu_count, process_line_init, [q])
    results = p.imap(process_line, n_line)
    for _ in range(number_of_lines):
        try:
            q.get(timeout=2)
        except queue.Empty:
            q.close()
            q.join_thread()
        yield results.next()
    p.close()
    p.terminate()
    p.join()
    pass

def yield_uniqueword_chunks(
    n_line: int = 10_000_000,
    chunksize: int = 1_787_000)-> Iterable[Set[str]]:
    chunk = set()
    for result in process_first_n_line(n_line):
        chunk.update(result)
        if len(chunk) > chunksize:
            yield chunk
            chunk = set()
    yield chunk

def main()-> None:
    for chunk in yield_uniqueword_chunks(
        n_line=1000, #Number of total comments to process
        chunksize=200 #number of unique words in a chunk (around 32MB)
        ):
        print(chunk)
        #export(chunk)

if __name__ == "__main__":
    main()


texts: Print Python docstrings when module is executed interactively

texts:
I have written a module, which should only be used by means of import, then call the functions as required.

I do not want this module to do anything when ran interactively, other than printing out the docstrings of all the functions, which have docstrings, and which are not starting with '_'

I am looking for tips/tricks to improve this code. Is there an alternative way, as I am not very skilled in the inspect module nor in sys.modules:

import sys
import inspect

def function1():
    """
    docstring of function1

    usage:

    import thismodule
    a = thismodule.function1()
    """
    pass

def function2():
    """
    docstring of function2

    usage:

    import thismodule
    a = thismodule.function2()
    """
    pass

def function3():
    #this function has not docstring
    #therefor should not be printed
    pass

def _function4():
    """
    this function has a docstring
    but the name starts with _ indicating an internal funciton

    this should not be printed
    """
    pass

def main():
    for name, obj in inspect.getmembers(sys.modules[__name__]):
        if (
            (inspect.isfunction(obj))         ## only functions
            and (obj.__module__ == __name__)  ## only for this module
            and (name[0:1] != '_')            ## no internals
            and (obj.__doc__ != None)         ## __doc__ must be defined
            ):
            print('****************************')
            print('function: ' + name + '()')
            print(obj.__doc__)
    print('****************************')

if __name__ == '__main__':
    main()


texts: Upload URLs of images as files to Parse.com

texts:
Using JavaScript cloud code, I'm trying to bulk convert a huge number of URL entries into actual files uploaded to Parse.com.

This code works; I just want to make it cleaner/nicer.

    Parse.Cloud.job("convertFiles", function(request, status) { //Cuts the rundata out of poor runs
    function sleep(milliseconds) {
      var start = new Date().getTime();
      for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds){
          break;
        }
      }
    }

    // Set up to modify user data
    Parse.Cloud.useMasterKey();

    var Debug = Parse.Object.extend("debugclass");
    var queryForDebugObj = new Parse.Query(Debug);
    queryForDebugObj.equalTo("objectId", "BsVP9W38yW");

    // Query for all users
    // var queryForSublist = new Parse.Query(Parse.Object.extend("Mini_test"));

    queryForDebugObj.find({
        success: function(results) {
            var debugObj = results[0];

            var processCallback = function(res) {
                    var entry = res[0];

                    Parse.Cloud.httpRequest({
                        url: entry.get("smallImage2"),
                        method: "GET",
                        success: function(httpImgFile)
                        {
                            console.log("httpImgFile: " + String(httpImgFile.buffer));
                            var imgFile = new Parse.File("picture.jpg", {base64: httpImgFile.buffer.toString('base64')});

                            imgFile.save().then(function () {
                                console.log("2");
                                entry.set("smallImage1", imgFile);
                                entry.save(null, {
                                  success: function(unused) {
                                    debugObj.increment("itemsDone");
                    sleep(50);
                                    res.shift();
                                    if (res.length === 0) {
                                        process(entry.id);
                                        return;
                                    }
                                    else {
                                        processCallback(res);
                                    }

                                  },
                                  error: function(unused, error) {
                                    response.error("failed to save entry");
                                  }
                                });
                            });
                        },
                        error: function(httpResponse)
                        {
                            console.log("unsuccessful http request");
                            response.error(responseString);
                        }
                    });
            };
            var process = function(skip) {{
                var queryForSublist = new Parse.Query("Mini_test");

                if (skip) {
                    queryForSublist.greaterThan("objectId", skip);
                    console.error("last object retrieved:" + skip);
                }
                queryForSublist.limit(1000);
                queryForSublist.ascending("objectId");
                queryForSublist.find().then(function querySuccess(res) {
                    processCallback(res);
                }, function queryFailed(reason) {
                    status.error("query unsuccessful, length of result " + result.length + ", error:" + error.code + " " + error.message);
                });
            }};

            process(debugObj.get("LastObject"));

        },
        error: function(error) {
            status.error("xxx Uh oh, something went wrong 2:" + error + "  " + error.message);
        }
    });
});


texts: Workaround for unchecked cast of a deserialized Object to ArrayList

texts:
For a class I was assigned to write code to read objects of the class Vehicle using ObjectInputStream (in). The objects are stored in an ArrayList called orders.

SSCE:

// Read all orders
Object obj = in.readObject();
orders = (ArrayList<Vehicle>) obj;

However, the compiler complains:

MacBook:Homework Brienna$ javac Orders.java -Xlint:unchecked
Orders.java:152: warning: [unchecked] unchecked cast
                    orders = (ArrayList<Vehicle>) in.readObject();
                                                                ^
  required: ArrayList<Vehicle>
  found:    Object
1 warning

I always try to improve my code instead of ignoring or suppressing warnings. In this case, I have come up with a solution, but I'm trying to understand why it works, and if there is a better solution.

This update stops the warning:

// Read all orders, casting each order individually
Object obj = in.readObject();
ArrayList ar = (ArrayList) obj;
for (Object x : ar) {
    orders.add((Vehicle) x);
}

Based on what I understand from what I've been reading, it works because (ArrayList<Vehicle>) obj may throw an exception if not all the elements are Vehicle. I am confused -- non-Vehicle objects can be added to the ArrayList even if its type parameter has been specified as Vehicle? Also, is there a better solution, e.g. using instanceof?


texts: String Trimmer and trimmed Input routine

texts:
As I thought about this question on SO, I realized that I wanted to implement either a string trimmer or a trimmed string inputter.

This is what I came up with, but I have a nagging feeling I could have done better.

Would you critique this, please?

#include <string>
#include <iostream>
#include <sstream>
#include <cassert>

template <typename Ch, typename Tr, typename Alloc>
void
trim(std::basic_string<Ch, Tr, Alloc>& str, const std::locale& loc)
{
  // (b,e)=ltrim(str)
  typename std::basic_string<Ch, Tr, Alloc>::const_iterator b = str.begin();
  typename std::basic_string<Ch, Tr, Alloc>::const_iterator e = str.end();
  while( b != e && std::isspace(*b, loc) )
    b++;

  // (b,e)=rtrim(b,e)
  // Query: this loop looks u-g-l-y. Can it be less ugly?
  while( b != e ) {
    e--;
    if(!std::isspace(*e, loc)) {
      e++;
      break;
    }
  }

  // str=(b,e)
  // Query: this string self-assigns (sort of). Is this UB?
  str.assign(b, e);
}

template <typename Ch, typename Tr, typename Alloc>
std::basic_istream<Ch,Tr>&
getTrimmedLine(std::basic_istream<Ch,Tr>& is,
  std::basic_string<Ch, Tr, Alloc>& str)
{

  // Get raw data from input
  std::getline(is, str);

  // And trim it
  trim(str, is.getloc());

  return is;
}

#define TEST
#ifdef TEST
template<typename T, std::size_t N>
std::size_t countof( T (& a)[N] ) { return N; }

int main () {
  const char * const inputs[] = {
    "simple", " front", "back ", " both ",
    "  front2", "back2  ", "  both2  ",
    "\n", "", "\n\n\n",
    "  \n", "  ", "  \n\n\n"
  };
  const char * const outputs[] = {
    "simple", "front", "back", "both",
    "front2", "back2", "both2",
    "", "", "",
    "", "", ""
  };

  assert(countof(inputs) == countof(outputs));

  for(std::size_t i = 0; i < countof(inputs); i++) {
    std::istringstream is(inputs[i]);
    std::string result;
    getTrimmedLine(is, result);
    assert(result == outputs[i]);
  }
}
#endif


texts: Copying folder contents from several folders

texts:
I have a file directory which contains folders for every month, and within those folders are several text files. In this context I would like to copy all of the text files from my January folder into a separate target folder. Then copy all of the text files within the February folder to the target folder, and so on for each month. This needs to happen sequentially and I'm not sure if I'm doing the iteration properly. I need the code to be able to run on several machines, and installing libraries on each is not possible.

Am I on the right track with the following? I'm not sure if this is the right approach to take or how to flesh this out.

function listdirectory(directory)
    local i, t, popen = 0, {}, io.popen
    for filename in popen('dir "'..directory..'" /b /ad'):lines() do
        i = i + 1
        t[i] = filename
    end
    return t
end

os.execute(xcopy folder_month target_folder)


texts:
I am writing a function in Typescript that involves checking a condition, doing some extra processing if the condition is satisfied, and then doing the bulk of the job.

Here's the catch: the extra processing stuff, that runs if the condition is satisfied, returns a promise. So instead of a clean, simple solution like this:

function openDoor(door) {
    if(door.locked) {
        door.unlock();
    }
    door.handle.turn();
    door.handle.push();
}

It turns into some horrible mess, like this:

function openDoor(door) {
    if(door.locked) {
        door.unlock().then(() => {
            door.handle.turn();
            door.handle.push();
        });
    } else {
        door.handle.turn();
        door.handle.push();
    }
}

Why, you ask?

Unlocking the door takes some time, and I can't turn and push the handle until it's done. Without code duplication, I wouldn't have time to unlock the door before pushing it.

So how can I make this better?

In the shortened example above, the duplicated section is quite small, but troublesome nonetheless. I would like to be able to make changes in a single place rather than two, when I update the code. So, how can I avoid code duplication while keeping my Promise?