HTML and JS to dynamically load, refresh, and execute JavaScript from external file The following code is designed to load and refresh JavaScript code from an external file sandbox.js and allow it to be refreshed dynamically and executed without reloading the entire page. The sandbox.js file is assumed to contain a function sandbox() which may contain arbitrary JavaScript code. As the title within the code below suggests, it's a sandbox intended for rapid testing of JavaScript code, where I can just save code in the IDE and execute the updated code immediately.

The most current version of this code is available here.

<!DOCTYPE html>

        <title>Sandbox</title>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="/JSDev/styles.css">

Sandbox

        <button id="refreshButton" onclick="loadScript('sandbox.js')">
            Refresh script
        </button>
        <button id="runButton" onclick="sandbox()">
            Run script
        </button>

        <button id="refreshRunButton" style="font-weight:bold"
                onclick="document.getElementById('refreshButton').click();
                         sandbox();">
            Refresh and run script
        </button>

This code is very clean, and I believe that it is a very useful tool for any JavaScript developer.

This is not very efficient:

<body onload="document.getElementById('refreshButton').click()">

Why? Well, think about what your code has to do:

Locate refreshButton.
Wait for refreshButton to load.
Find its onclick method and call it.

Sure, this isn't terribly inefficient, but it can be made simpler.

I see what you are trying to do by not having the HTML code memorize anything; everything is handled in references which all boils down to a few elements.

While this is nice, it would be much more efficient if you called refreshButton's onclick method itself. So, you would just call loadScript:

<body onload="loadScript('sandbox.js')">

This:

if(js !== null)

Can be reduced to this:

if(js)

I think the way I wrote it is better, because the way I read your code is like this:

  If the functions that JS is loaded with returned null...

And I read what I wrote as:

  If JS exists...

This may just be me, however.

The reason why you can make this change is because, in JavaScript, null is a falsey value and therefore can be treated as though it were false.

Be careful with that runButton button. If the user acts too fast by quickly reloading the script and then trying to run it, there could be some problems; what if the script has not loaded yet?

Rather than silently failing and leaving a non-technically inclined user dumbfounded, it would be better to notify the user of problem (and prevent failing due to an attempt at trying to run a currently non-existent function).

Read this StackOverflow post for some ways you could check if the script has loaded.

In your case, you already have your work laid out for you: the sandbox.js source file creates a global sandbox function that you try to call.

Therefore, you can write this to make sure that the script has loaded:

if(typeof sandbox !== "undefined") {
    sandbox();
} else {
    window.alert("The script has not been loaded yet!");
}

In response to this comment:

  "append the newly-created script element to the head": I'm following
  the JS book I'm studying from (I'm a neophyte at JS and the DOM,
  coming from C++). In fact, JS may not necessarily be best in head.
  (//stackoverflow.com/q/10994335)

This is a different response to that comment.

It doesn't matter where you put the scripts now that the browser has already fully loaded. The browser is not going to stop again and load the code (even if it did, that would be good (referencing to my response comment)).


Checking for items in sublists Today I'll demonstrate a simple function that searches for a item in all sublists of a list. For this it uses iteration, and keep in mind that it can be slow because of this. How can I improve it? Linked lists?

I doubt __contain__ can do the same.

def ListContainWSublist(searchfor, *args):

    Result = False

    for x in args:
        if type(x) == list:
            Result = ListContainWSublist(searchfor, *x)

        if x == searchfor:
            Result = True

    return Result

Proper type checking

To start off, you shouldn't be type checking like this:

if type(x) == list:
    ...

The proper way to go is to use Python's isinstance(a, b) function, where a is a value, and b is the type you're checking against. The portion of your code that involves type checking would be re-written like this:

if isinstance(x, list):
    ...

The difference here is that isinstance allows for inheritance when checking the type of a value, rather than simply checking the type of the value itself, which can be rather useful. If you're interested, you can read more about this at this Stackoverflow question.

Nitpicks

You should have the user pass a list of values, not pass a variable amount of arguments. Your function signature should look like this:

def list_contain_sublist(search_for, collection):
    ...

Your names are rather nasty, especially for Python. In Python, variable and function names should be in snake_case, and classes should be in PascalCase. Not the other way around.

There's also no need for the Result variable. You can change this line:

Result = ListContainWSublist(searchfor, *x)

To this:

return ListContainWSublist(searchfor, *x)

This line:

Result = True

Should become:

return True

And then this line:

Result = False

Can be removed all-together.

Other than those things, it looks fine. There may be a way to do this without recursion, but I'm not sure how to. I'll leave that up to you to figure out.


Replace all the occurrence of a string I have the following function to replace all the occurrence of a string that matches certain token.

public string ReplaceTokenBySample(string StingValue)
{
    List<Token> tokens = GetTokenList();
    foreach (var token in tokens)
    {
        StingValue = StingValue.Replace(token.Token, token.SampleValue);
    }
    return StingValue;
}

GetTokenList(); will return

Token                   SampleValue
##Username##            John Doe
##UserEmail##           john.doe@domain.com
##UserFirstName##       John
##UserLastName##        Doe

How can I optimize this code?

Full console app code is as follows:

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

namespace Rextester
{
    public class Token
    {
        public string TokenValue { get; set; }
        public string SampleValue { get; set; }
    }
    public class Program
    {
        public List<Token>GetTokenList()
        {
            List<Token> tokens = new List<Token>
            {
                new Token(){ TokenValue = "##Username##", SampleValue="John Doe" },
                new Token(){ TokenValue = "##UserEmail##", SampleValue="john.doe@domain.com " },
                new Token(){ TokenValue = "##UserFirstName##", SampleValue="John" },
                new Token(){ TokenValue = "##UserLastName##", SampleValue="Doe"}
            };
            return tokens;
        }

        public string ReplaceTokenBySample(string StringValue)
        {
            List<Token> tokens = GetTokenList();
            foreach (var token in tokens)
            {
                StringValue = StringValue.Replace(token.TokenValue, token.SampleValue);
            }
            return StringValue;
        }

        public static void Main(string[] args)
        {
            Program obj = new Program();
            string StringValue ="Hello ##Username##! I have emailed you at ##UserEmail##. ##UserFirstName## ##UserLastName## how is you days going on. Have a good day ##Username##. ";
            Console.WriteLine(obj.ReplaceTokenBySample(StringValue));
        }
    }
}

If this is your real use-case then I'd not go beyond the obvious optimizations. In this case you're creating a new string for each replacement, you can use StringBuilder.Replace() instead:

public string ReplaceTokenBySample(string value)
{
    var result = new StringBuilder(value);
    GetTokenList().ForEach(x => result.Replace(x.TokenValue, x.SampleValue));

    return result.ToString();
}

If instead of List<Token> you have IEnumerable<Token> (or if you want to avoid List<T>.ForEach()) then you can use:

public string ReplaceTokenBySample(string value)
{
    GetTokenList().Aggregate(new StringBuilder(value),
        (result, item) => result.Replace(item.TokenValue, item.SampleValue));

    return result.ToString();
}

Few things to consider:

You're performing ordinal case-sensitive comparison, it seems to be appropriate to replace placeholders with their actual value and it has the benefit to be reasonably fast. If this is not the case then you should definitely go with t3schb0t's answer (which handles this properly and it's incredibly more readable.)
Parameters should be camelCase.
It's usually confusing to overwrite parameters value with something else (especially for non trivial code), compiler is able to optimize your code to get the best of it even when using a local variable.

Few more notes about overall design: you do not validate your parameters anywhere, if they're only used internally to your assembly then mark them internal or private (as appropriate) and ASSERT about their content (for example: why do you declare Token as public?)

Names sound little bit strange, you do not need to repeat the type in the name: TokenSample and TokenValue inside the Token class (and StringValue for a value of type String).

If you intend to fill Token programmatically then adding a Token(string, string) ctor may help to keep your code shorter.


Best way to pass a 2d array to functions which size is unknown at compile time in pure C I've been wondering for some time what the best way to pass a 2d array to functions is. I know that arrays, passed to functions, decay into pointers, so int arr[25] would become int *arr inside a function. The problem is with 2d arrays, int arr[5][5] would not become int **arr. Instead I've been taught to pass it like this: int (*arr)[5]. The problem with that is that the final square brackets need to have a size parameter inside and it needs to be known at compile time.

I've looked around and found this answer which, I believe, has the best solution. The idea is to pass the 2 dimensions separately and the location of the data. So, the function's signature would be like this:

void print(void *arr, size_t rows, size_t cols);

Then, we create a temporary array, which we can use conventionally, like this:

int (*temp)[cols] = (int (*)[cols]) arr;

I wrote some code to test this and it works.

#include <stdio.h>

void fill(void * arr, size_t rows, size_t cols, int val);
void print(void * arr, size_t rows, size_t cols);

int main(void) {
  size_t iArr = 5, jArr = 3;
  int arr[iArr][jArr];
  fill(arr, iArr, jArr, 0x45);
  print(arr, iArr, jArr);
  return 0;
}

void fill(void * arr, size_t rows, size_t cols, int val)
{
  int (*temp)[cols] = (int (*)[cols])arr;
  for(size_t i = 0; i < rows; i++)
  {
    for(size_t j = 0; j < cols; j++)
    {
      temp[i][j] = val;
    }
  }
  arr = temp;
}

void print(void * arr, size_t rows, size_t cols)
{
  int (*temp)[cols] = (int (*)[cols])arr;
  for(size_t i = 0; i < rows; i++)
  {
    for(size_t j = 0; j < cols; j++)
    {
      printf("%3d ", temp[i][j]);
    }
    putchar('\n');
  }
}

This can also be tested here. I'm curious whether this will work always without errors. I tested it with all kinds of sizes and, again, no problem there. Can this be improved further? Could there be any edge cases where this breaks (checks for valid arguments or making sure the size passed doesn't exceed the stack size are omitted here, as that's not the point of this question).

Type-wise, it is ok to go from void pointers to array pointers and back. As long as the "effective type" is an int array of the specified size. Void pointers do however have non-existent type safety, so they should be avoided for that reason.

The best way is rather to use an array and let the compiler "adjust" it to an array pointer between the lines:

void fill (size_t rows, size_t cols, int arr[rows][cols], int val);

The VLA syntax requires that rows and cols exist, so arr must be declared on the right side of them in the parameter list. Please note that this is still a pointer and not a whole VLA passed by value - we can't pass arrays by value in C.

Fixed example:

#include <stdio.h>

void fill(size_t rows, size_t cols, int arr[rows][cols], int val);
void print(size_t rows, size_t cols, int arr[rows][cols]);

int main(void) {
  size_t iArr = 5, jArr = 3;
  int arr[iArr][jArr];
  fill(iArr, jArr, arr, 0x45);
  print(iArr, jArr, arr);
  return 0;
}

void fill(size_t rows, size_t cols, int arr[rows][cols], int val)
{
  for(size_t i = 0; i < rows; i++)
  {
    for(size_t j = 0; j < cols; j++)
    {
      arr[i][j] = val;
    }
  }
}

void print(size_t rows, size_t cols, int arr[rows][cols])
{
  for(size_t i = 0; i < rows; i++)
  {
    for(size_t j = 0; j < cols; j++)
    {
      printf("%3d ", arr[i][j]);
    }
    putchar('\n');
  }
}


Resetting a password I am trying to reset a password when password_reset_token is received in the controller. But it's becoming a long if else ladder of many conditions. Can it be reduced in a better way?

def set_new_password
    if params[:password_reset_token].present?
      @user = User.find_by(password_reset_token: params[:password_reset_token])
      if @user.present?
        if params[:password] != params[:password_confirmation]
          render json: {errors: ["Your password confirmation doesn't match"]}, status: :unprocessable_entity
        elsif @user.password_reset_sent_at < 2.hours.ago
          render json: {errors: ["Your password reset expired. Please require a new password reset from the app."]}, status: :unprocessable_entity
        elsif @user.update(user_params)
          @user.update(password_reset_token: nil, password_reset_sent_at: nil)
          render :json => {:success => true}
        end
      else
         render json: {errors: ["Password reset not found. Please request a new password reset!"]}, status: 404
      end
    else
      render json: {errors: ["Password reset not found. Please request a new password reset!"]}, status: 404
    end
  end

Below is refactoring code you can use:

def set_new_password
  @user = User.find_by(password_reset_token: params[:password_reset_token]) if params[:password_reset_token].present?

  unless user
    render json: {
       errors: ["Password reset not found. Please request a new password reset!"]
    }, status: 404 and return
  end

  if params[:password] != params[:password_confirmation]
    render json: { errors: ["Your password confirmation doesn't match"] }, status: :unprocessable_entity

  elsif @user.password_reset_sent_at < 2.hours.ago
    render json: {
      errors: ["Your password reset expired. Please require a new password reset from the app."]
    }, status: :unprocessable_entity

  else
    updated_params = user_params.merge(password_reset_token: nil, password_reset_sent_at: nil)

    @user.update(updated_params) ?
      render :json => {:success => true} :
      render :json => {:success => false}
  end
end

I also suggest to move validation password confirmation match with password to model using standard ActiveRecord validation: http://guides.rubyonrails.org/active_record_validations.html#confirmation


Updating items in a list from a blocking source asynchronously This is a Windows forms application.
this.Server.GetLogMessages() will block if there are no messages to get, so I want this in a separate thread. I'm putting the messages into a ConcurrentStack and then pulling them out on the main thread to output them.
Here is the respective code:
private async Task UpdateLogs()
{
    var logMessages = new ConcurrentStack<string>();

    // assign to `_` to avoid warning
    var _ = Task.Run(async () =>
    {
        await foreach (var message in this.Server.GetLogMessages())
        {
            logMessages.Push(message);
        }
    }, this.CancellationTokenSource.Token);

    await foreach (var message in GetMessages())
    {
        // don't update the UI if task is canceled
        if (this.CancellationTokenSource.Token.IsCancellationRequested)
        {
            break;
        }

        this.textLogs.AppendText($"{message}{Environment.NewLine}");
    }

    async IAsyncEnumerable<string> GetMessages()
    {
        var message = String.Empty;

        while (!this.CancellationTokenSource.IsCancellationRequested)
        {
            while (!logMessages.TryPop(out message))
            {
                await Task.Delay(100);
            }

            yield return message;
        }
    }
}

It works fine, but seems as if it could be better/cleaner somehow.

My try to simplify and prettify the method.
Avoid using globals in async code, pass Token as argument.
// optimized out async State Machine
private Task UpdateLogsAsync(IProgress<string> status, CancellationToken token) => Task.Run(async () =>
{
    await foreach (var message in this.Server.GetLogMessages().WithCancellation(token))
    {
        status.Report(message);
    }
}, token);

Usage
// synchronized callback. Create new in UI Thread and its body will be always executed there.
IProgress<string> status = new Progess<string>(message =>
{
    this.textLogs.AppendText($"{message}{Environment.NewLine}");
});
try
{
    await UpdateLogsAsync(status, this.CancellationTokenSource.Token);
}
catch (OperationCanceledException ex)
{
    status.Report(ex.Message);
}


VBA code to import data, doing lookups to detect duplicates I have an import macro, which creates ID by concatenating cells, then I compare using VLOOKUP with another sheet if any duplicate found.

It's running very slowly, so I want to know better ways to optimize this code, because once finished, I will need to add another "for" for to handle duplicates found and compare dates.

It's one of my first macros in VBA, so I'm sure there are a lot of ways to improve the performance.

Sub ImportData()

Dim wb1 As Workbook
Dim wb2 As Workbook
Dim slr As Long
Dim dlr As Long
Dim Tlr As Long

Set wb1 = ActiveWorkbook

FileToOpen = Application.GetOpenFilename _
(Title:="Select import file", _
FileFilter:="Microsoft Excel Workbooks (*.xls;*.xlsx;*.xlsm),*.xls;*.xlsx;*.xlsm")

If FileToOpen = False Then
    MsgBox "No File Specified.", vbExclamation, "ERROR"
    Exit Sub
Else
    Set wb2 = Workbooks.Open(Filename:=FileToOpen)
    slr = wb2.Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row

    wb2.Worksheets("Sheet1").Range("A8:S" & slr).Copy _
    wb1.Worksheets("INPUT_DATA").Range("A2")
End If

    wb2.Close savechanges:=False

    dlr = wb1.Worksheets("INPUT_DATA").Cells(Rows.Count, 1).End(xlUp).Row
    wb1.Worksheets("INPUT_DATA").Range("A2:S" & dlr).ClearFormats

    For cell = 2 To dlr
        Cells(cell, 20).Formula = "=CONCAT(RC[-19], ""__"",RC[-18])"
    Next

    'check duplicate values before import to TOTAL_DATA
    Tlr = wb1.Worksheets("TOTAL_DATA").Cells(Rows.Count, 1).End(xlUp).Row
    countMatch = 0
    countUnmatch = 0
    For cell = 2 To dlr
        Cells(cell, 21).Formula = "=IF(ISNA(VLOOKUP(RC[-1],TOTAL_DATA!C30,1,FALSE)), ""No"", ""Yes"")"
            If Cells(cell, 21).Value = "Yes" Then
                Cells(cell, 20).Font.Color = vbRed
                countMatch = countMatch + 1
            Else
                Range("A" & cell, "T" & cell).Cut Destination:=wb1.Worksheets("TOTAL_DATA").Range("A" & Tlr + 1)
                Tlr = Tlr + 1
                countUnmatch = countUnmatch + 1
            End If
    Next cell

    If countMatch > 0 Then
            MsgBox "Found duplicates!!" & vbCr & "Number of duplicates : " & countMatch & _
            vbCr & "Duplicate items were keep at INPUT_DATA" & vbCr & _
            "Loaded succesfully : " & countUnmatch & " items", vbExclamation
    Else
            MsgBox "Loaded succesfully : " & countUnmatch & " items"
    End If
End Sub
```

This should be twice as fast:

dlr = wb1.Worksheets("INPUT_DATA").Cells(Rows.Count, 1).End(xlUp).Row
wb1.Worksheets("INPUT_DATA").Range("A2:S" & dlr).ClearFormats

'check duplicate values before import to TOTAL_DATA
    Tlr = wb1.Worksheets("TOTAL_DATA").Cells(Rows.Count, 1).End(xlUp).Row
    countMatch = 0
    countUnmatch = 0

For cell = 2 To dlr
    Cells(cell, 20).Formula = "=CONCAT(RC[-19], ""__"",RC[-18])"

    Cells(cell, 21).Formula = "=IF(ISNA(VLOOKUP(RC[-1],TOTAL_DATA!C30,1,FALSE)), ""No"", ""Yes"")"
    If Cells(cell, 21).Value = "Yes" Then
        Cells(cell, 20).Font.Color = vbRed
        countMatch = countMatch + 1
    Else
        Range("A" & cell, "T" & cell).Cut Destination:=wb1.Worksheets("TOTAL_DATA").Range("A" & Tlr + 1)
        Tlr = Tlr + 1
        countUnmatch = countUnmatch + 1
    End If
Next cell

Because in here we loop only once from 2 to dlr.


Building a very basic calculator I have been a VB developer for couple of years, but strictly using functional programming paradigms — I just started using object-oriented paradigms a few days ago, and want some advice on how to improve.

I'm writing a small calculator application in order to understand VB.NET object-oriented principles. The program is (currently) working perfect the way I've done it (following some books and tutorials), and I want to get some response on how I'm doing regarding following OOP principles, paradigms and practices.

The program flow is pretty simple, and as follows:

The user enters the first number to add;
The user enters the second number to add;
The user clicks on the "calculate" button;
The UI (through Label2) updates to show the result;

The code is mostly done through the main class Cls_addition:

Public Class Cls_addition

    'Variable de Classe
    Private term1 As Integer
    Private term2 As Integer
    Private resultat As Long

    'Properties
    Public Property termA() As Integer
        Get
            Return term1
        End Get

        Set(ByVal value As Integer)
            term1 = value
        End Set
    End Property

    Public Property termB() As Integer
        Get
            Return term2
        End Get

        Set(ByVal value As Integer)
            term2 = value
        End Set
    End Property

    'Methods
    Public Function additioner(ByVal term1 As Integer, ByVal term2 As Integer) As Long
        resultat = term1 + 0 + term2
        Return resultat
    End Function

End Class

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim totalAddition As New Cls_addition           'Creation d'un obejct (creation nouvelle instance d'un obeject a l'aide du mot clé "New")

    totalAddition.termA = TextBox1.Text.Trim        'Object.Proprieté
    totalAddition.termB = TextBox2.Text.Trim        'Object.Proprieté

    Label2.Text = totalAddition.additioner(totalAddition.termA, totalAddition.termB)

End Sub

And I have also attached a picture of the form itself:

Welcome to the world of OOP — hopefully there are a few things we can teach you. ;)

I'm going to show you an alternative implementation first, to help you see how OOP truly should be used, then I'll discuss your specific issues.

When building a calculator it's hard to effectively build something dynamic, you are always concerned about how things should relate (for example, how do we represent \$a+b+c\$, as \$(a + b) + c\$, as \$a + (b + c)\$, or some other way?), but it's often easiest if you consider each term and operation on it's own.

Let's take \$+\$, for example, we should have two terms: a left and a right. But what is a term?

A term can be any of the following:

A value (\$1\$, for example);
Another expression / operation (\$a + b\$, for example);

What do they have in common? They all have a Value property. So, in order to represent this we start with an interface:

Public Interface ITerm
    Property Value As Double
End Interface

Pretty simple, and we'll define a ConstantTerm:

Public Class ConstantTerm
    Implements ITerm

    Public Sub New(value As Double)
        Me.Value = value
    End Sub

    Public Property Value As Double Implements ITerm.Value
End Class

So far so good, we have a ConstantTerm which is just set to a value, so we can now build an AdditionTerm:

Public Class AdditionTerm
    Implements ITerm

    Public Sub New(left As ITerm, right As ITerm)
        Me.Value = left.Value + right.Value
    End Sub

    Public Property Value As Double Implements ITerm.Value
End Class

So now, to do our math, we just need to do:

Dim result As Double = _
    New AdditionTerm( _
        New ConstantTerm(CDbl(TextBox1.Text.Trim)), _
        New ConstantTerm(CDbl(TextBox2.Text.Trim))).Value

But even better: this sets us up for success later when we want to add a SubtractionTerm:

Public Class SubtractionTerm
    Implements ITerm

    Public Sub New(left As ITerm, right As ITerm)
        Me.Value = left.Value - right.Value
    End Sub

    Public Property Value As Double Implements ITerm.Value
End Class

And it also sets us up for parsing things later on down the road. (Since we don't care about values, we only care about terms, a parser just has to define a term as it goes and supply them as arguments to the next term.)

Regarding your specific code, there are a few things to take note of:

In .NET we pretty much always try to name classes, interfaces, enums, and properties PascalCase — instead of Cls_addition we would use ClsAddition;
When you set totalAddition.TermA and TermB, you should try to use a safer parsing system, via {NumericType}.TryParse:

Dim value As Integer = 0
If Integer.TryParse(TextBox1.Text.Trim(), value) Then
    'Parse was successful
Else
    'Show the user an error message, perhaps
End If

Always name things what they mean, and not what they are: TextBox1 is a bad name, it should be firstTermInput, etc.;
More recent versions of VB.NET support automatically-implemented properties, such as Property TermA As Integer, instead of manually specifying a Getter and Setter;

Overall, good start, and I hope you continue to learn and improve as you experiment and continue. :)


Python CLI-Parser improvement for "one of those options" I was wondering if there was a better way to implement my cli parser.

For context:
I need to pass to my script either a file in one of two formats or two files in a specific format.

It may be easier to understand like this:

file.ext1 OR file.ext2 OR (file_1.ext2 AND file_2.ext2)

I've used python argparse add_mutually_exclusive_group successfully and it looks like this:

import argparse
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
    "--ext1",
    type    = __existant_file,
    metavar = "FILE",
    help    = "input file (format ext1)"
)
group.add_argument(
    "--ext2",
    type    = __existant_file,
    metavar = "FILE",
    help    = "input file (format ext2)"
)
group.add_argument(
    "--paired",
    nargs   = 2,
    type    = __existant_file,
    metavar = ("MATE_1", "MATE_2"),
    help    = "input file (two files format ext2)"
)

args = parser.parse_args()
print(args)

if args.ext1 is not None:
  file = args.ext1
elif args.ext2 is not None:
  file = args2.ext2
else:
  file = args.paired[0]
  file2 = args.paired[1]

Which is used as:

python script.py --ext1 file
OR
python script.py --ext2 file
OR
python script.py --paired file_1 file_2

Which is working but not really smooth. Do you have any lead of how I can improve the CLI parser ?

Okay, I found a better way

import argparse
parser = argparse.ArgumentParser()

class RequiredLen(argparse.Action):
        def __call__(self, parser, args, values, option_string=None):
            if not 1 <= len(values) <= 2:
                msg = f"argument {self.dest} requires 1 or 2 arguments"
                raise argparse.ArgumentTypeError(msg)
            setattr(args, self.dest, values)
# Just give me 1 or 2 files
parser.add_argument(
    "--paired",
    nargs    = '+',
    action   = RequiredLen,
    required = True,
    help     = "input file(s)"
)
# Specify either ext1 or ext2 format
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
    "--ext1",
    action = "store_const",
    dest   = "format",
    const  = "ext1",
    help   = "input is ext1 format"
)
group.add_argument(
    "--ext2",
    action = "store_const",
    dest   = "format",
    const  = "ext2",
    help   = "input is ext2 format"
)
args = parser.parse_args()
print(args)

This way I can later just use something like:

def process_ext1(l: list):
   print("ext1 file(s)")
   for i in l:
       print(i)

def process_ext2(l: list):
   print("ext2 file(s)")
   for i in l:
       print(i)

process_format = { 'ext1': process_ext1, 'ext2': process_ext2 }
process_format[args.format](args.paired)


Java Pong implementation I was making a pong game when I realized (by looking at other people's examples) that my Pong code was very messy and not organized. I would like to ask for assistance.

import java.awt.*;
import java.awt.Component;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;

public class Pong {

  JFrame frame;
  //JButton up;
  //JButton down;
  JTextField controls;
  MyDrawPanel drawPanel;
  int y = 325;
  int edge;
  int bx = 650;
  int by = 325;
  boolean gameOn = true;

  public static void main(String[] args) {
    Pong game = new Pong();
    game.go();
  }

  public void go() {

    frame = new JFrame();
  //  up = new JButton();
    //down = new JButton();
    controls = new JTextField();
    drawPanel = new MyDrawPanel();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(controls);
    controls.requestFocus();
    controls.addKeyListener(new keyListener());
    frame.setTitle("Pong");
    frame.setSize(1366,768);
    frame.getContentPane().setBackground(Color.black);

  /*  up.setText("UP");
    up.setBackground(Color.white);
    up.addActionListener(new upListener());
    down.setText("DOWN");
    down.setBackground(Color.white);
    down.addActionListener(new downListener());

    frame.getContentPane().add(BorderLayout.SOUTH, down);
    frame.getContentPane().add(BorderLayout.NORTH, up); */
    frame.getContentPane().add(drawPanel);

    frame.setVisible(true);

    while(gameOn) {

    }
  }

  class keyListener implements KeyListener {
    public void keyPressed(KeyEvent e) {
    //  int id = e.getID();
      char key = e.getKeyChar();
      //System.out.println("Key Pressed" + " " + key);

      if(key == 'w' && y > 0) {
        y = y-4;
        drawPanel.repaint();
        edge = 0;
      }

      else if(key == 's' && y < 560) {
        y = y+4;
        drawPanel.repaint();
        edge = 0;
      } else {
        if(edge < 3) {
        System.out.println("edge");
        edge++;
       }
      }
    }

    public void keyReleased(KeyEvent e) {

    }

    public void keyTyped(KeyEvent e) {

    }
  }

/*  class upListener implements ActionListener {
    public void actionPerformed(ActionEvent event) {
      System.out.println("left");
      for(int i = 20; i > 0; i--) {
        Timer timer = new Timer(5, this);
      //  timer.setInitialDelay(19000);
        timer.start();
        y--;
        drawPanel.repaint();
      }
    }
  }
  class downListener implements ActionListener {
    public void actionPerformed(ActionEvent event) {
      System.out.println("right");
      y = y + 10;
      drawPanel.repaint();
    }
  } */
  class MyDrawPanel extends JPanel {

    public void paintComponent(Graphics g) {
      g.setColor(Color.black);
      g.fillRect(0,0,this.getWidth(),this.getHeight());

      g.setColor(Color.white);
      g.fillRect(1300,y,30,150);

      g.setColor(Color.white);
      g.fillOval(bx,by,20,20);
    }
  }
}

Thanks for sharing your code.

Naming

Finding good names is the hardest part in programming, so always take your time to think about the names of your identifiers.

Naming Conventions

Please read and follow the Java Naming Conventions

eg.:

Let class names always start with an uppercase letter
let boolean variables and methods returning a boolean value start with is, has, can or alike. (isGameRunning vs. gameOn)

Choose you names from the problem domain, not from the technical solution.

eg.: your class keyListener might better be named PadelControl

don't use comments to "save" code

Modern IDEs keep a history of the last saved versions of your code files. They have capability to compare with this old versions and get them back (or parts of). Also using a source code management system like git or svn is quite easy for the same purpose.

So there is no need to keep "inactive code" as comments in your code files. just remove them.

use adapter classes if possible

Almost all Swing interfaces have empty implementation classes called *Adapter in your case it is the KeyAdapter. You can extend that class and only implement the method you need, keeping your code clean from the empty implementation of the unneeded methods.

do not add code with unknown/unverified behavior

You method go() ends with an empty loop.
I suspect you added this because you thought you program would exit otherwise. Maybe you have been told to do so or red somewhere.
But you most likely never tested that behavior.

This empty loop results in 100% activity of one of your CPUs cores. Some years ago, when there was only one core your computer would have been unusable after the start of your program. Thanks to technology advance this loop does not stall your PC.

So never add code just because it sounds like a good idea, always test that certain code really has the expected effect. If it doesn't delete it immediately.

  There is a programing technique called Test Driven Development supporting that.


Caesar encryption and decryption For a small project, I had to implement Caesar encryption in Swift(4). I'm mainly looking for performance optimizations.

This whole code should be copy and pasteable in a playground and is functioning as expected as far as I can see.

import Foundation

let caesarNumber:Int = 7;

let alphabet_array:[Character] = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

func encode(inputString: String) -> String {
   var resultString:String = ""

   for char in inputString {
       for i in 0...(alphabet_array.count-1) {
           if (char == alphabet_array[i]) {
               if (i + caesarNumber < alphabet_array.count-1) {
                   resultString.append(alphabet_array[i+caesarNumber])
               }
               else {
                   let subscripture:Int = (i+caesarNumber)%alphabet_array.count
                   resultString.append(alphabet_array[subscripture])
               }
           }
       }
   }
   return resultString
}

func decode(inputString: String) -> String {
   var resultString:String = ""

   for char in inputString {
       for i in 0...(alphabet_array.count-1) {
           if (char == alphabet_array[i]) {
               if (i - caesarNumber >= 0) {
                   resultString.append(alphabet_array[i-caesarNumber])
               }
               else {
                   resultString.append(
                      alphabet_array[alphabet_array.count+(i-caesarNumber)])
               }
           }
       }
   }
   return resultString
}

   let encodedString = encode(inputString: "zacharias")
   let decodeString = decode(inputString: encodedString);

Naming

According to the Swift API Design Guidelines, variable names are lower camel case (not alphabet_array),
and types should not be part of the variable name (not caesarNumber, inputString, resultString).

It is also clear that the first (and only) argument of encode() and decode()
is the input string, here we can omit the argument label:

func encode(_ input: String) -> String

which is then called as

let encodedString = encode("zacharias")

Improving the API

The current API has two drawbacks:

It uses the global variable caesarNumber to pass information to the
functions.
The function names (“encode”, “decode”) are too common, they to not tell
what the function actually does.

Here are two alternative suggestions:

Make the function names more specific, and pass the shift amount as an
additional argument.

You can also define a default parameter value for the shift amount.

func caesarEncode(_ input: String, shiftBy: Int = 7) -> String
func caesarDecode(_ input: String, shiftBy: Int = 7) -> String

Define a cipher type with parameters, and encode/decode methods.

That would allow to substitute the Caesar cipher by other methods easily.

struct CaesarCipher {
    let shiftAmount: Int

    init(shiftAmount: Int = 7) {
        self.shiftAmount = shiftAmount
    }

    func encode(_ input: String) -> String { ... }
    func decode(_ input: String) -> String { ... }
}

Example usage:

let rot13 = CaesarCipher(shiftAmount: 13)
let encrypted = rot13.encode("Hello World")

I'll stick with the first API for the remainder of this review.

Simplify the code

The alphabet can be initialized simply with

let alphabet: [Character] = Array("abcdefghijklmnopqrstuvwxyz")

because a String is a sequence of its Characters. Locating a character
in the array can be done with

if let idx = alphabet.index(of: char) { ... }

instead of a loop. The test for

 if (i + caesarNumber < alphabet_array.count-1)

is not needed, because the “else case” (with the modulo arithmetic) works actually in both cases, with or without wrap-around.

Summarizing the above suggestions so far, we have for the encoding method:

func caesarEncode(_ input: String, shiftBy: Int = 7) -> String {
    var result: String = ""
    for char in input {
        if let idx = alphabet.index(of: char) {
            let newIdx = (idx + shiftBy) % alphabet.count
            result.append(alphabet[newIdx])
        }
    }
    return result
}

Decoding is the same as encoding, only with a shift in the opposite direction.
If we modify the encoding method slightly to work with negative shift amounts then it can be used for the decoding as well:

func caesarEncode(_ input: String, shiftBy: Int = 7) -> String {
    var result: String = ""
    for char in input {
        if let idx = alphabet.index(of: char) {
            var newIdx = (idx + shiftBy) % alphabet.count
            if newIdx < 0 { newIdx += alphabet.count }
            result.append(alphabet[newIdx])
        }
    }
    return result
}

func caesarDecode(_ input: String, shiftBy: Int = 7) -> String {
    return caesarEncode(input, shiftBy: -shiftBy)
}

Improve the performance

For optimal performance on really long strings you can operate on the
UTF-16 view instead, that allows to determine the offset within the alphabet with pure integer arithmetic instead of the array lookup.

Enumerating the UTF-16 view also seems to be faster than enumerating
the characters (which represent extended grapheme clusters).

A possible implementation could look like this:

func caesarEncode(_ input: String, shiftBy: Int = 7) -> String {
    let letterA = Int("a".utf16.first!)
    let letterZ = Int("z".utf16.first!)
    let letterCount = letterZ - letterA + 1

    var result = [UInt16]()
    result.reserveCapacity(input.utf16.count)

    for char in input.utf16 {
        let value = Int(char)
        switch value {
        case letterA...letterZ:
            let offset = value - letterA
            var newOffset = (offset + shiftBy) % letterCount
            if newOffset < 0 { newOffset += letterCount }
            result.append(UInt16(letterA + newOffset))
        default:
            break
        }
    }

    return String(utf16CodeUnits: &result, count: result.count)
}

On my computer this was faster than the previous method (3 milliseconds
instead of 11 milliseconds for a string with 100,000 characters).

For shorter strings that probably won't matter, and you can choose what you
feel more familiar with.


Concurrent access to data with QReadWriteLock Using Qt, I've got this code in order to protect access to some shared data between threads. I'm pretty sure the idea is correct, but I don't know if RVO and/or RAII could potentially screw the get function. I'm much more used to C and while I understand the idea, I'm not totally familiar with all the "gotchas" for these two concepts.

class DataManager {
    Q_OBJECT

private:
    QVector<DataType> data;
    QReadWriteLock* rwLock;

public:
    DataManager() {
        rwLock = new QReadWriteLock();
    }
    ~DataManager() {
        delete rwLock;
    }
    Q_DISABLE_COPY(DataManager)

    QVector<DataType> getData() {
        QReadWriteLocker lock(rwLock);
        return data;
    }
    QVector<DataType>* beginModifyData() {
        rwLock->lockForWrite();
        return &data;
    }
    void endModifyData() {
        rwLock->unlock();
        emit dataChanged();
    }

signals:
    void dataChanged();
};

In the get function, is it possible that the RAII-type class QReadWriteLocker unlocks the lock before the return copy is made? Thus allowing some thread, that was waiting to write, to overwrite the data being returned.

Also, if somebody writes

QVector<DataType>& myData = dataManager->getData();

Is it possible, due to RVO, that they get a reference to the actual data?

Also, I'd like to receive comments on the code and idea itself. Below I've outlined the reasons why I chose this approach.

Simple to use. Since one can only read a copy of the data, they don't have to worry about synchronization and locking.
Taking advantage of the implicit sharing of Qt containers, no actual copies will ever be made when using getData(), thus making read-only access very fast.
Since, when modifying the data, one gets a pointer to the actual data, again, in most cases, no copies will be made, unless some thread is caching the data (or one of the copies has not yet gone out of scope of whatever got it).
Looking at the documentation and code, a non-recursive QReadWriteLock is ultra fast in the non-contended case, not doing any waiting or context-switching (uses atomic operations on an integer).
I could potentially do some data validation/fixup in the endModifyData function if needed.

Thanks.

Locking
Let's see what these member functions actually do, and what can go wrong:
getData
The lock acquired in getData basically only ensures that nobody is currently modifying data while inside. As soon as the caller gets the returned value, another thread is free to modify it.
To be a bit clearer, this is how RAII breaks down:
QVector<DataType> getData() {
    QReadWriteLocker lock(rwLock);
    QVector<DataType> temp = data;
    lock.~QReadWriteLocker(); // unlock
    return temp;
}

So the lock doesn't actually cover subsequent usage.
beginModifyData/endModifyData
These two member functions expect to be called in tandem. But what happens if the caller to beginModifyData forgets to call endModifyData (e.g. because an exception was thrown)? Obviously, in that case the lock never gets released.
Also, somebody might store the returned pointer, thus having unsynchronized access to the data after the lock got released.
General stuff
Is there any specific reason why rwLock has to be a pointer? It could simply be of type QReadWriteLock instead.
Is there any specific reason why beginModifyData returns a QVector<DataType>* instead of a QVector<DataType>&?
Your question regarding RVO
No, that is not how return value optimization (RVO) works. For a better understanding, if the compiler applies RVO it might conceptually rewrite the code to something similar to this:
void getData(QVector<DataType>* return_value) {
    QReadWriteLocker lock(rwLock);
    // construct a new QVector<DataType> at the given address (to be passed from the callsite)
    new(return_value) QVector<DataType>(data);
}

// the callsite would be rewritten from
QVector<DataType> myData = dataManager->getData();
// to
QVector<DataType> myData; // uninitialized!
dataManger->getData(&myData);

So this obviously won't work with a reference.
Without RVO, the reference won't work at all, as the lifetime of the returned object ends at the end of its declaration. However, it will work (at least partially) for a const QVector<DataType>& as lifetimes of temporaries get extended for those (though it will still refer to the copy).


Checking date & time in PHP Goal: To create a countdown to our next available live stream.

Details: We live stream six times a week all (PST).
1. Sunday at 8:00 a.m.
2. Sunday at 10:00 a.m.
3. Sunday at 12:00 p.m.
4. Sunday at 6:30 p.m.
5. Wednesday at 7:00 p.m.
6. Saturday at 10:00 a.m.

My approach: I check what day it is and what time it is then create the countdown to the next stream.

I'm sure what I have done can be cleaned up and improved, so tell me how.

<?php
// Countdown Stuff
$year = date(Y);
$month = date(m);
$month_day = date(d);
$day = date(w);
$hour = date(G);
$min = date(i);
$addDay = 0;

// It's Sunday
if ( $day == 0 ) {
    if ( $hour < 8 ) {
       $hour = 8;
       $min = 0;
    }
    else if ( $hour < 10 ) {
       $hour = 10;
       $min = 0;
    }
    else if ( $hour < 12 ) {
       $hour = 12;
       $min = 0;
    }
    else if ( $hour <= 18 && $min < 30 ) {
       $hour = 18;
        $min = 30;
    }
    else {
     $addDay = 3;
       $hour = 19;
       $min = 0;
    }
}
// It's Monday
else if ( $day == 1 ) {
    $addDay = 2;
      $hour = 19;
      $min = 0;
}
// It's Tuesday
else if ( $day == 2 ) {
    $addDay = 1;
      $hour = 19;
      $min = 0;
}
// It's Wednesday
else if ( $day == 3) {

    if ( $hour < 19 ) {
       $hour = 19;
       $min = 0;
    } else {
     $addDay = 3;
       $hour = 10;
       $min = 0;
    }
}
// It's Thursday
else if ( $day == 4 ) {
    $addDay = 2;
      $hour = 10;
      $min = 0;
}
// It's Friday
else if ( $day == 5 ) {
    $addDay = 1;
      $hour = 10;
      $min = 0;
}
// All that's left is Saturday
else {

    if ( $hour < 10 ) {
       $hour = 10;
       $min = 0;
    } else {
     $addDay = 1;
       $hour = 8;
       $min = 0;
    }
}

$build_date = $year . '-' . $month . '-' . $month_day . ' ' . $hour . ':' . $min . ':00';
$date = new DateTime($build_date);

if ( $addDay ) {
    $date->modify("+$addDay day");
}

$date = strtotime($date->format("Y-m-d G:i:s"));
$now = strtotime("now");
$count = $date - $now;
?>

<script type="text/javascript">
var myTime = <?=$count?>;
$('#countdown').countdown({ until: myTime});
</script>

To add to Andrew's answer about taking advantage of what type of timestamps can be creating using strtotime(), your code can be reduced to around 25 lines...

<?php

$schedule = array(
    'this Sunday 8am',
    'this Sunday 10am',
    'this Sunday 12pm',
    'this Sunday 6:30pm',
    'this Wednesday 7pm',
    'this Saturday 10am'
    );

$current_time = strtotime('now');
foreach ($schedule as &$val) {
    $val = strtotime($val);
    // fix schedule to next week if time resolved to the past
    if ($val - $current_time < 0) $val += 604800;
    }
sort($schedule);
$countdown = $schedule[0] - $current_time;

?>

<script type="text/javascript">
    var myTime = <?php echo $countdown; // just personally prefer full tags ?>;
    $('#countdown').countdown({ until: myTime});
</script>

To add to visionary-software-solutions' answer, it would be best to store the schedule in a database or a separate xml/text/json/etc type file.  This way, you can have staff simply use an internal webform to change schedules instead of having the PHP dev hard-code the changes every time.  In that webpage, you can allow staff to only select a weekday and time, and have the page translate that into a string usable by strtotime() in this countdown script.

Edit: fixed strtotime() values.  Careful with "this day" vs "next".  For some insight into what type of strings strtotime() can take, see: http://www.gnu.org/software/tar/manual/html_node/Date-input-formats.html


Common client server implementation I have created a common C file for a basic client server. It works fine on my Linux setup. Please provide your comments/suggestions on how the code can be optimized/enhanced.

After compiling we need to give parameters "s" or "c" to executable from the command line to run it as a server or client respectively. The client connects to the server at the default IP of 192.168.7.2.

#include"stdio.h"
#include"stdlib.h"
#include"sys/types.h"
#include"sys/socket.h"
#include"string.h"
#include"netinet/in.h"
#include"pthread.h"
#include"netdb.h"
#include"errno.h"
#include"signal.h"

#define PORT 4444
#define BUF_SIZE 2000
#define CLADDR_LEN 100
#define MAX_ALLOWED_CONNECTIONS 5
char * whoAmI;
int sockfd, len, ret, newsockfd;

void * receiveMessage(void * socket) {
 int sockfd, ret;
 char buffer[BUF_SIZE];
 sockfd = (int) socket;
 memset(buffer, 0, BUF_SIZE);
 for (;;) {
  memset(buffer, 0, BUF_SIZE);
  ret = recvfrom(sockfd, buffer, BUF_SIZE, 0, NULL, NULL);
  if (ret < 0) {
   printf("Error receiving data!\n");
  } else {
   if(*whoAmI == "c") {
        printf("server: ");
    }
    else {
        printf("client: ");
    }
   fputs(buffer, stdout);
   //printf("\n");
  }
 }
}

void  INThandler(int sig)
{
    printf("Closig all sockets");
    close(newsockfd);
    close(sockfd);
    exit(0);
}
void main(int argc, char**argv) {
 struct sockaddr_in addr, cl_addr;

 char buffer[BUF_SIZE];
 pid_t childpid;
 char clientAddr[CLADDR_LEN];
 pthread_t rThread;

 /* install signal handler to close sockets on ctrl+c from user */
 signal(SIGINT, INThandler);

if (argc < 2) {
  printf("Needs arguments: 0==Server; 1==client\n");
  exit(1);
}

whoAmI = argv[1];

printf("whoami = %s \n", whoAmI);
 sockfd = socket(AF_INET, SOCK_STREAM, 0);
 if (sockfd < 0) {
  printf("Error creating socket!\n");
  exit(1);
 }
 printf("Socket created...\n");

 memset(&addr, 0, sizeof(addr));

// start of server
if ((strcmp(whoAmI, "s") == 0) ) {
 addr.sin_family = AF_INET;
 addr.sin_addr.s_addr = INADDR_ANY;
 addr.sin_port = PORT;

/* Naming the socket */
 //strcpy(addr.sun_path,"server_socket");

     ret = bind(sockfd, (struct sockaddr *) &addr, sizeof(addr));
     if (ret < 0) {
      printf("%s",strerror(errno));
      printf("Error binding!\n");
      exit(1);
     }
     printf("Binding done...\n");

     printf("Waiting for a connection...\n");
     listen(sockfd, MAX_ALLOWED_CONNECTIONS);

     len = sizeof(cl_addr);
     newsockfd = accept(sockfd, (struct sockaddr *) &cl_addr, &len);
     if (newsockfd < 0) {
      printf("Error accepting connection!\n");
      exit(1);
     }

     inet_ntop(AF_INET, &(cl_addr.sin_addr), clientAddr, CLADDR_LEN);
     printf("Connection accepted from %s...\n", clientAddr);
    }//end of server
    else {
//start of client
    addr.sin_family = AF_INET;
     addr.sin_addr.s_addr = inet_addr("192.168.7.2");
     addr.sin_port = PORT;
           ret = connect(sockfd, (struct sockaddr *) &addr, sizeof(addr));
         if (ret < 0) {
          printf("Error connecting to the server!\n");
          exit(1);
         }
         printf("Connected to the server...\n");
    //very important step
    newsockfd = sockfd;
// end of client
    }

 memset(buffer, 0, BUF_SIZE);
 printf("Enter your messages one by one and press return key!\n");

 //creating a new thread for receiving messages from the client
 ret = pthread_create(&rThread, NULL, receiveMessage, (void *) newsockfd);
 if (ret) {
  printf("ERROR: Return Code from pthread_create() is %d\n", ret);
  exit(1);
 }

 while (fgets(buffer, BUF_SIZE, stdin) != NULL) {
  ret = sendto(newsockfd, buffer, BUF_SIZE, 0, (struct sockaddr *) &cl_addr, len);
  if (ret < 0) {
   printf("Error sending data!\n");
   exit(1);
  }
 }

 close(newsockfd);
 close(sockfd);

 pthread_exit(NULL);
 return;
}

Who am I?

When skimming the code, it's not obvious to a reader what the significance of checking whether a string starts with the letter "c".

if(*whoAmI == "c") {
    ...
} else {
    ...
}

In addition, this construct introduces bugs – what if the user were to type something other than "c" or "s"?

I think you should instead parse the argument once and define an enum to be tested against.

enum running_mode { SERVER, CLIENT };
enum running_mode running_mode;

// ...

if (0 == strcmp(argv[1], "c") {
    running_mode = CLIENT;
} else if (0 == strcmp(argv[1], "s") {
    running_mode = SERVER;
} else {
    printf("Argument must be 'c' or 's'\n");
    exit(1);
}

// ...

if (running_mode == CLIENT) {
    // handle client case
} else {
    // handle server case
}

You should also provide a more helpful message if there are not 2 arguments to the program. "0==Server; 1==client" seems a bit misleading.

Commented out code

I consider leaving commented out lines in your code without explanation a bad practise. Let me quote @nhgrif in this answer:

  Source control should help you keep track of code that used to be there, so there's not a real good excuse to leave it there for any historical reason.

  Arguably, you might want to leave it in if it's something you're frequently uncommenting for some sort of testing purposes, but if that's the case, perhaps leave a comment above the line, something to the effect of:

// Uncomment the following line to ...

Because you use source control, right?

Indentation

The indentation in the posted code is a mess. I don't know if that's a consequence of copy-pasting the code or if it actually looks that way on your machine. To get any kind of grip on your code I had to run it through an auto-indent program first.

If you don't know the common practices, here is a general rule of thumb: whenever there is a {, increase indentation by one, and whenever there is a }, decrease indentation again. Other lines in the code should use the same level of indentation as the previous line.

Complex main

The main function is quite long and complex. You have acknowledged this yourself by leaving the comments "start of server", "end of server" etc in the code. Instead of this, I recommend refactoring the server and client specific code into separate functions. Any common data could then be passed to these functions by main.

Void main

You declare main as returning void, and then use exit(1) to signal an unsuccessful result to the OS. I think you should instead declare int main and use a return statement instead of exit.

Signal handler

The behavior of INThandler is undefined, because only very specific standard library functions can be called from signal handlers (Cppreference).

  If the signal handler is called NOT as a result of abort or raise (in
  other words, the signal handler is asynchronous), the behavior is
  undefined if the signal handler calls any function within the standard
  library, except

  abort
  _Exit
  quick_exit
  signal with the first argument being the number of the signal currently handled (async handler can re-register itself, but not other
  signals).
  atomic functions from stdatomic.h if the atomic arguments are lock-free
  atomic_is_lock_free (with any kind of atomic arguments)

The program might still work on your machine, but is not guaranteed to do so on any box.

On the other hand, you don't need this signal handler at all. When a program terminates on modern operating systems, resources like open files are automatically released by the OS. The only purpose I see the handler serving is printing out "Closing all sockets", which seems a bit useless to me.

Implicit delcarations

You've forgot to include some header files.

unistd.h containing close.
arpa/inet.h conataing inet_ntop and inet_addr.

Global variables

Use of global variables is generally frowned upon. They make programs much harder to read and reason about. Of course they are sometimes required, but in your case they could just as easily be local variables passed around as function parameters.

Type correctness

The type of len should be socklen_t, not int. If not that, at least an unsigned integer type.

Buffer size

You define a macro BUF_SIZE with an arbitrary value (I assume). There's no need to do this as stdio.h already has a macro specifically for this purpose called BUFSIZ. The value of the macro "is chosen on each system so as to make stream I/O efficient" (GNU Manual).

Conclusion

I think this is a great beginner project! Writing network code is always interesting. To summarize most of my points above, code is read more times than written, so think about the reader!


Translating LaTeX documents into different languages using DeepL API I'm coming from C and C++ and have often troubles using Python's full potential. This is a script I wrote to translate LaTeX documents into different languages. A parser replaces all latex specific syntax with hashes and then sends it all to deepl. The pydeepl wrapper is from Github.

What do you think of this code?

import sys
import re
import pydeepl
from random import choice
from tqdm import tqdm

def make_xlat(*args, **kwds):
    adict = dict(*args, **kwds)
    rx = re.compile('|'.join(map(re.escape, adict)))
    def one_xlat(match):
        return adict[match.group(0)]
    def xlat(text):
        return rx.sub(one_xlat, text)
    return xlat

if __name__ == "__main__":
     fileInputName = sys.argv[1]
     #fileInputName = "Introduction.tex"
     fileOutName = fileInputName.split('.')[0]+"_trans.tex"

     fileIn  = open(fileInputName, "r")
     fileOut = open(fileOutName, "w")

     fileStr = fileIn.read()

     print("Starting hashing...")

     #replace commands like \begin{*}, \end{*}, tabs etc. with hashes
     searchObj1 = re.findall( r"\\begin\{\w+\}|\t|    |\r|\\end\{\w+\}|\\usepackage\{\w+\}|\\newcommand\{\w+\}|\\include\{.*\}|\\input\{\w+\}|\\\w+\[.*\}|\%.*", fileStr)
     #random number for every found command + a prefix which hopefully doens't appear in text. Used to skip lines later, which don't need translation
     list1 = ['X#X' + str(choice(range(1111, 9999, 1))) for x in searchObj1]
     #make a dictionary out of hashes
     d1 = dict(zip(searchObj1,list1))
     translate = make_xlat(d1)
     hashedText = translate(fileStr)

     #replace all latex commands (starting with a backslash) with hashes
     searchObj2 = re.findall( r"\\\w+",hashedText)
     #random number  + prefix again
     list2 = ['X#X' + str(choice(range(1111, 9999, 1))) for x in searchObj2]
     #make a dictionary
     d2 = dict(zip(searchObj2,list2))
     translate = make_xlat(d2)
     hashedText = translate(hashedText)
     #print(hashedText)
     #fileOut.write(translate(hashedText))

     d1.update(d2) # combine dictionaries
     #with open('hash_dict.json', 'w') as f:
     #json.dump(d1, f)

     print("Hashing done. Starting translation...")

     translated = ''
     for line in tqdm(hashedText.splitlines()): #tqdm is a progressbar
         #print(line)
         if line.startswith("X#X") and len(line) == 7:
             translated = translated + line + '\n'
             continue
         if line == '\n':
             translated = translated + '\n'
         elif line == '':
             translated = translated + '\n'
         else:
             translated = translated+pydeepl.translate(line, "DE", "EN")+'\n'
     #translated = translated+pydeepl.translate(hashedText, "DE", "EN")
     #print(translated)

     d1Inv = {val:key for (key, val) in d1.items()} #swap dictionary
     translate2 = make_xlat(d1Inv)
     fileStrOut = translate2(translated)
     #print(fileStrOut)

     fileOut.write(fileStrOut)

     print("success")
     fileIn.close()
     fileOut.close()

EDIT 1: One flaw I already know is that I'm sending sentences by sentences which makes it really slow. However, sending all lines at once produces errors which I couldn't get rid of. Deepl scrambles stuff around and dehashign doesn't work anymore.

While using sys.argv is fine for a first version of a program, you should give it a proper CLI. It would be nice if multiple latex files could be passed (since it is common to split a large project into multiple files) and also to specify the source and target languages. For this you can use argparse:

import argparse

def parse_args(args=None):
    parser = argparse.ArgumentParser()
    parser.add_argument("--from", default="DE", help="Language of the source document(s)")
    parser.add_argument("--to", default="EN", help="Language of the target document")
    parser.add_argument("file", nargs="+", help="Path(s) to the latex file(s)")
    return parser.parse_args(args)

if __name__ == "__main__":
    args = parse_args()
    print(args.to, args.from, args.file)
    ...

This even gives you a nice usage message when calling the script with the option -h or --help:

usage: script_name.py [-h] [--from FROM] [--to TO] file [file ...]

positional arguments:
  file         Path(s) to the latex file(s)

optional arguments:
  -h, --help   show this help message and exit
  --from FROM  Language of the source document(s)
  --to TO      Language of the target document

Now, let's get to your "hashing". When randomly selecting from \$H = 9999 - 1111 = 8888\$ values, it takes on average \$Q(H) = \sqrt{\tfrac{\pi}{2}H}\approx 118.16\$ draws until you get a number twice. In other words, if you have more than about 120 elements, you will overwrite some. And that number is actually less than half of that because you separately hash \begin and \end.

One way to avoid collisions is to just keep on counting up. For this you could use itertools.count, which produces an infinite stream of increasing numbers, starting with the argument (or 0 if not given), when being iterated:

from itertools import count

counter = count(1111)
assert len(searchObj1) + len(searchObj2) <= 8888, "Too many objects to hash"
list1 = ['X#X{}'.format(i) for _, i in zip(searchObj1, counter)]
list2 = ['X#X{}'.format(i) for _, i in zip(searchObj2, counter)]

Another way to make it less likely is to extend the range. And at that point you might as well use the built-in hash function:

list1 = ['X#X{}'.format(hash(x)) for x in searchObj1]

In this case you would need to relax the and len(line) == 7 requirement later.
When opening files, you should use the with keyword to ensure they are properly closed, even if an exception occurs somewhere in the block:

with open(fileInputName) as fileIn, open(fileOutName, "w") as fileOut:
    ...

You should also think about better names. Python has an official style-guide, PEP8, which recommend using lower_case instead of camelCase. In addition, list1, searchObj1, d2 are all not very good names.
Doing string addition can be very costly, because in Python strings are immutable. This means that when you do str_a + str_b, Python has to allocate a new string object of length len(str_a) + len(str_b) and then copy the content of both strings into that new array. This takes more time the longer the strings are and the more often you do it. Since you are adding strings of the length of a full document and are doing so in a loop, this can be very slow.

Instead, build a list and str.join it at the end:

translated = []
for line in fileIn:
    #print(line)
    if line.startswith("X#X") and len(line) == 7:
        translated.append(line)
    elif not line.strip():
        translated.append('')
    else:
        translated.append(pydeepl.translate(line, args.from, args.to))
translated = '\n'.join(translated)

Note that I directly iterate over the file (since files are iterable), meaning that this program is less limited by the amount of memory available. However this means that the progress bar does not work anymore (and I therefore removed it here), because it needs to know how many lines there are. You can use something like this to add it back: https://blog.nelsonliu.me/2016/07/29/progress-bars-for-python-file-reading-with-tqdm/


Citadel's VisualEncrypt and VisualDecrypt I was skimming through this paper out of boredom. On pages 5 and 6, the paper shows a simple encryption/decryption scheme that Citadel uses to obfuscate data. The algorithm basically XORs the next character with the previous character. The code is roughly this (ugly, I know):

void VisualEncrypt (void *buffer, unsigned size) {
  for (unsigned i = 1; i < size; ++i) {
      ((unsigned char *) buffer) [i] ^= ((unsigned char *) buffer) [i - 1] ;
  }
}

void VisualDecrypt (void *buffer, unsigned size) {
  if (!size) {
      return ;
  }

  for (unsigned i = size - 1; i > 0; --i) {
      ((unsigned char *) buffer) [i] ^= ((unsigned char *) buffer) [i - 1] ;
  }
}

I decided to make a more generic version of this code so that it could work on different containers and values:

template <class InputIterator, class OutputIterator>
OutputIterator VisualEncrypt (InputIterator begin, InputIterator end, OutputIterator destination)
{
    if (begin == end) {
        return destination ;
    }

    auto value = *begin ;
    *destination++ = value ;

    while (++begin != end) {
        value ^= *begin ;
        *destination++ = value ;
    }

    return destination ;
}

template <class InputIterator, class OutputIterator>
OutputIterator VisualDecrypt (InputIterator begin, InputIterator end, OutputIterator destination)
{
    if (begin == end) {
        return destination ;
    }

    auto value = *begin ;
    *destination++ = value ;

    while (++begin != end) {
        auto temp = *begin ;
        *destination++ = value ^ temp ;
        value = temp ;
    }

    return destination ;
}

template <class Iterator>
Iterator VisualEncrypt (Iterator begin, Iterator end)
{
    return VisualEncrypt (begin, end, begin) ;
}

template <class Iterator>
Iterator VisualDecrypt (Iterator begin, Iterator end)
{
    return VisualDecrypt (begin, end, begin) ;
}

Here are two sample cases of it being used:

#include <iterator>
#include <string>
#include <vector>

int main ()
{
    // Test char
    std::string plaintext = "Please encrypt me!" ;

    std::vector <unsigned char> cyphertext ;
    VisualEncrypt (plaintext.cbegin (), plaintext.cend (), std::back_inserter (cyphertext)) ;

    std::string decrypttext ;
    VisualDecrypt (cyphertext.cbegin (), cyphertext.cend (), std::back_inserter (decrypttext)) ;

    // Test long
    long arr [] = {1, 2, 3, 4, 5} ;
    const auto size = sizeof (arr) / sizeof (arr [0]) ;
    VisualEncrypt (arr, arr + size) ;
    VisualDecrypt (arr, arr + size) ;

    return 0 ;
}

The code seems to work fine. I want to make sure I'm not misusing the iterators and invoking undefined behavior. I couldn't find a clean way to simplify any of this with the <algorithm> library. Any tips on that would be great too.

The way you handle the first element as a special case is cumbersome: you're basically unrolling the first iteration of the loop.  You could just initialize value = 0 so that the first XOR just copies the input to the output.

template <class InputIterator, class OutputIterator>
OutputIterator VisualEncrypt (InputIterator begin, InputIterator end, OutputIterator destination)
{
    typedef typename std::iterator_traits<InputIterator>::value_type T;
    T value = 0;
    while (begin != end) {
        value ^= *begin++;
        *destination++ = value ;
    }

    return destination ;
}

template <class InputIterator, class OutputIterator>
OutputIterator VisualDecrypt (InputIterator begin, InputIterator end, OutputIterator destination)
{
    typedef typename std::iterator_traits<InputIterator>::value_type T;
    T value = 0;

    while (begin != end) {
        T temp = *begin++;
        *destination++ = value ^ temp ;
        value = temp ;
    }

    return destination ;
}

Alternatively, use a for-loop, which results in slightly more compact code and gets the pesky side-effect ++ operators out of the way.

template <class InputIterator, class OutputIterator>
OutputIterator VisualEncrypt(InputIterator begin, InputIterator end, OutputIterator destination)
{
    typedef typename std::iterator_traits<InputIterator>::value_type T;
    for (T value = 0; begin != end; ++begin, ++destination) {
        *destination = (value ^= *begin);    // <-- Probably controversial one-liner
    }

    return destination;
}

template <class InputIterator, class OutputIterator>
OutputIterator VisualDecrypt(InputIterator begin, InputIterator end, OutputIterator destination)
{
    typedef typename std::iterator_traits<InputIterator>::value_type T;
    for (T value = 0; begin != end; ++begin, ++destination) {
        T temp = *begin;
        *destination = value ^ temp;
        value = temp;
    }

    return destination;
}


Find element in sorted matrix Find an element in a MxN matrix where each row and column is sorted in ascending order.

Any comments on my code?
(I added some test cases on non square matrices which I did not copy here)

import static org.junit.Assert.*;

import org.junit.Test;

public class Sol {

  public class Coord{
    int x;
    int y;

    public Coord(int _x, int _y){
      x = _x;
      y = _y;
    }
  }

  public Coord findElt(int[][] matrix, int elt, int begin_row, int end_row,
          int begin_col, int end_col){

    if (end_row < begin_row || end_col < begin_col){
      return new Coord(-1, -1);
    }

    if (begin_row == end_row && begin_col == end_col && matrix[begin_row][begin_col] != elt){
      return new Coord(-1, -1);
    }

    int mid_row = (begin_row + end_row)/2;
    int mid_col = (begin_col + end_col)/2;
    int current = matrix[mid_row][mid_col];

    if (current == elt){
    return new Coord(mid_row, mid_col);
  }

    else{
      Coord ur = findElt(matrix, elt, begin_row, mid_row, mid_col + 1, end_col);

      if (ur.x >= 0){
        return ur;
      }

      Coord bl = findElt(matrix, elt, mid_row + 1, end_row, begin_col, mid_col);

      if (bl.x >= 0){
        return bl;
      }

      if (elt > current){
        return findElt(matrix, elt, mid_row + 1, end_row, mid_col + 1, end_col);
      }
      else{
        return findElt(matrix, elt, begin_row, mid_row, begin_col, mid_col);
      }
    }

  }

  public Coord findElt(int[][] matrix, int elt){
    return findElt(matrix, elt, 0, matrix.length-1, 0, matrix[0].length-1);
  }

  @Test
  public void test_0(){
    int[][] mat = new int[3][3];

    mat[0][0] = 1;
    mat[0][1] = 2;
    mat[0][2] = 3;
    mat[1][0] = 2;
    mat[1][1] = 3;
    mat[1][2] = 5;
    mat[2][0] = 3;
    mat[2][1] = 4;
    mat[2][2] = 7;

    assertEquals(-1, findElt(mat, 8).x);
    assertEquals(-1, findElt(mat, 8).y);
  }

  @Test
  public void test_1(){
    int[][] mat = new int[3][3];

    mat[0][0] = 1;
    mat[0][1] = 2;
    mat[0][2] = 3;
    mat[1][0] = 2;
    mat[1][1] = 3;
    mat[1][2] = 5;
    mat[2][0] = 3;
    mat[2][1] = 4;
    mat[2][2] = 7;

    assertEquals(0, findElt(mat, 1).x);
    assertEquals(0, findElt(mat, 1).y);
  }

  @Test
  public void test_2(){
    int[][] mat = new int[3][3];

    mat[0][0] = 1;
    mat[0][1] = 2;
    mat[0][2] = 3;
    mat[1][0] = 2;
    mat[1][1] = 3;
    mat[1][2] = 5;
    mat[2][0] = 3;
    mat[2][1] = 4;
    mat[2][2] = 7;

    assertEquals(1, findElt(mat, 3).x);
    assertEquals(1, findElt(mat, 3).y);
  }

  @Test
  public void test_3(){
    int[][] mat = new int[3][3];

    mat[0][0] = 1;
    mat[0][1] = 2;
    mat[0][2] = 3;
    mat[1][0] = 2;
    mat[1][1] = 3;
    mat[1][2] = 5;
    mat[2][0] = 3;
    mat[2][1] = 4;
    mat[2][2] = 7;

    assertEquals(2, findElt(mat, 7).x);
    assertEquals(2, findElt(mat, 7).y);
  }

  public static void main(String[] args){
    int N = 3;
    int[][] mat = new int[N][N];
    Sol ex = new Sol();

    mat[0][0] = 1;
    mat[0][1] = 2;
    mat[0][2] = 3;
    mat[1][0] = 2;
    mat[1][1] = 3;
    mat[1][2] = 5;
    mat[2][0] = 3;
    mat[2][1] = 4;
    mat[2][2] = 7;

    ex.test_0();
    ex.test_1();
    ex.test_2();

    Coord a = ex.findElt(mat, 4);
    System.out.println(a.x + " " + a.y);

  }
}

When creating matrices, you can use the more concise syntax

int[][] m = {
  { 1, 2, 3 },
  { 2, 3, 5 },
  { 3, 4, 7 }
};


Counting integers that are within intervals I am looking for a more efficient way than bruteforcing my way through in the following problem in python 3.

Problem statement:

Input:

An array of n integers, scores, where each score is denoted by scores_j
An array of q integers, lowerLimits, where each lowerLimits_i denotes
the lowerLimit for score range i.
An array of q integers, upperLimits, where each upperLimits_i denotes
the upperLimit for score range i.

Output: A function that returns an array of Q integers where the value at each index i denotes the number of integers that are in the inclusive range [lowerLimits_i, upperLimits_i].

Constraints:

1 ≤ n ≤ 1e5
1 ≤ scores_j ≤ 1e9
1 ≤ q ≤ 1e5
1 ≤ lowerLimits_i ≤ upperLimits_i ≤ 1e9

Example:
Given scores= [5, 8, 7], lowerLimits = [3, 7], and upperLimits = [9, 7]
I want to check how many of the integers are contained in each interval (inclusive). In this examples: intervals are [3,9] and [7,7], and the result would be [3, 1].

My code looks like this:

def check(scores, lowerLimits, upperLimits):
   res = []
   for l, u in zip(lowerLimits, upperLimits):
       res.append(sum([l <= y <= u for y in scores]))
   return res
if __name__ == "__main__":
   scores= [5, 8, 7]
   lowerLimits = [3, 7]
   upperLimits = [9, 7]

   print(check(scores, lowerLimits, upperLimits))

If you sort your values, you can then make an iterator on the sorted list, forward it to the lower limit, count until the first value is reached that is larger than the upper limit and discard all further values.

The sorting will add \$\mathcal{O}(n\log n)\$ time complexity, but if you have a lot of values larger than (all) your upper bounds, you could get this back.

An implementation using itertools could be:

from itertools import dropwhile, takewhile

def graipher(scores, lower, upper):
    scores = sorted(scores)
    for l, u in zip(lower, upper):
        s = iter(scores)
        yield sum(1 for _ in takewhile(lambda x: x <= u, dropwhile(lambda x: x < l, s)))

Since the scores are now already sorted, you could even use bisect to find the right indices to insert the upper and lower limits. The difference between the two indices will give you the number of values in range:

from bisect import bisect_left, bisect_right

def graipher2(scores, lower, upper):
    scores = sorted(scores)
    for l, u in zip(lower, upper):
        yield bisect_right(scores, u) - bisect_left(scores, l)

Both functions are generators. You can just call list() on them to consume them into a list, giving the same result as your code:

if __name__ == "__main__":
   scores= [5, 8, 7]
   lowerLimits = [3, 7]
   upperLimits = [9, 7]

   print(check(scores, lowerLimits, upperLimits))
   print(list(graipher(scores, lowerLimits, upperLimits)))
   print(list(graipher2(scores, lowerLimits, upperLimits)))

Finally, Python has an official style-guide, PEP8, which recommends using lower_case for variables and functions.

When running your function and my two functions on an input of the maximum defined size for scores and a single pair of limits, I get the following timings:

check: 249 ms ± 3.84 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
graipher: 77.3 ms ± 950 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
graipher2: 53.9 ms ± 772 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

When using a scores of length 10 and the maximum defined size for the lengths of the limits, I get:

check: 2.8 s ± 112 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
graipher: 246 ms ± 2.77 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
graipher2: 73.1 ms ± 612 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

And finally, when using the maximum defined size for both scores and the limits, only graipher2 finishes in a reasonable time (I stopped the other ones after a few minutes):

graipher2: 247 ms ± 4.94 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

So, to summarize, sort your scores and use bisection.


Intersection-detection algorithm This is an intersection-detection algorithm I developed as an alternative method to the one developed for my coursework. I won't post some of the other functions as they are used in the coursework too, feel free to ask if their names aren't self explanatory. This function simply returns whether 2 bcw objects are intersecting. bcw objects are either boxes or circles. What I'd like is any comments on my algorithm/coding style to help make me a better programmer.

def bcw_do_collide_i(obj_A,obj_B,tracer=None, accuracy = 30):
    """ Check whether Box-Circle World objects obj_A
    and obj_B collode. If so, return True,
    otherwise return False.
    """
    # items to be checked
    comp1 = [obj_A]
    comp2 = [obj_B]

    # does a component circumcircle collide, True = collides
    truth1 = [False]
    truth2 = [False]

    # Depth used to limit iterations to accuracy
    depth = 0

    while len(comp1)!=0 and depth<accuracy:
        # Find any non colliding components
        for c1,t1 in zip(comp1,range(len(truth1))):
            circum_1 = bcw_circumcircle(c1)
            for c2,t2 in zip(comp2,range(len(truth2))):
                circum_2 = bcw_circumcircle(c2)
                if tracer <> None:
                    tracer([c1,c2,circum_1,circum_2], ["k--","b--","r--","r--"])
                if bcw_do_circles_overlap(circum_1,circum_2) == True:
                    truth1[t1] = True
                    truth2[t2] = True
                    # Check for colliding components
                    in_1 = bcw_incircle(c1)
                    in_2 = bcw_incircle(c2)
                    if tracer <> None:
                        tracer([c1,c2,in_1,in_2],
                           ["g--","b--","r--","r--"])
                    if bcw_do_circles_overlap(in_1,in_2): return True

        # Subdivide all components whose outers collide
        sub = []
        for c1,t1 in zip(comp1,truth1):
            if t1:
                sub+=bcw_components(c1)

        comp1 = sub[::]
        truth1 = [False for i in comp1]

        sub =[]
        for c2,t2 in zip(comp2,truth2):
            if t2:
                sub+=bcw_components(c2)

        comp2 = sub[::]
        truth2 = [False for i in comp1]
        depth+=1

    return False

I was tempted by using the bcw objects as dictionary keys but they had to be mutable.

A few quick stylistic things:

Don't use <>, its considered an older style use != instead
When comparing against None, use "x is None" not "x <> None" or "x != None" This is because there is only one None object so its more correct to compare object identity
Don't use == True or == False. There are some corner cases that won't do what you expect. They clutter your code and make it look like you don't know what you are doing.
Your variables do not provide much hints about what they are doing. For example you have variables named truth. Given that we already knew there were holding booleans thats not very useful.

To actually rework your code:

You set values in a truth list, then use those values to decide whether or not to take an action. Flags clutter code. Rather then setting those flags, why don't we maintain a list. By adding a remaining_Comp1 and remaining_comp2 list I push elements in there instead of setting Truth values in my list. This completely eliminates the neccesity of keeping the truth lists and eliminates a lot of the code.
You have two for loops which iterate over all possible combinations of elements from your two lists. By using itertools.product, we can make this simpler
You check that comp1 is not empty, but not comp2. This looks like an oversight.
You are keeping track of depth to make sure you don't go into too much detail. But you've basically reimplemented a for loop. I'd move depth into a for loop and simply bail out with a break statement if comp1 or comp2 is empty.
Rather then checking whether trace is None, I recommend using a NullTracer which simply does nothing when it is called.

Your code reworked:

def bcw_do_collide_i(obj_A,obj_B,tracer=None, accuracy = 30):
    """ Check whether Box-Circle World objects obj_A
    and obj_B collode. If so, return True,
    otherwise return False.
    """
    if tracer is None:
        tracer = NullTracer()

    # items to be checked
    comp1 = [obj_A]
    comp2 = [obj_B]

    for depth in range(accuracy):
        if not comp1 or not comp2:
            return False

        remaining_comp1 = []
        remaining_comp2 = []
        # Find any non colliding components
        for c1, c2 in itertools.product(comp1, comp2):
            circum_1 = bcw_circumcircle(c1)
            circum_2 = bcw_circumcircle(c2)
            tracer([c1,c2,circum_1,circum_2], ["k--","b--","r--","r--"])
            if bcw_do_circles_overlap(circum_1,circum_2):
                remaining_comp1.append(c1)
                remaining_comp2.append(c2)
                # Check for colliding components
                in_1 = bcw_incircle(c1)
                in_2 = bcw_incircle(c2)
                tracer([c1,c2,in_1,in_2],
                   ["g--","b--","r--","r--"])
                if bcw_do_circles_overlap(in_1,in_2): return True

        # Subdivide all components whose outers collide
        def expand_components(components):
            result = []
            for c1 in remaining_comp1:
                result += bcw_components(components)
            return result

        comp1 = expand_components(remaining_comp1)
        comp2 = expand_components(remaining_comp2)

    return False


How to find contradiction in order of items in multiple sequences Suppose you have several sequences:

  A: 1  2  3  4  5
  B: 2  4  5
  C: 2  1  3  4  5
  D: 3  2

Here, some pairs of list contradicts each other, because they don't expose the same order for their similar elements: (A,C) (A,D) (C, D)

What is an algorithm or a linq statements to find such pairs? Or just to say if my sequences have such a contradiction or not! I store these sequences in a list of lists of strings

 List<List<String>> Sequences;

This is my code for the problem:

    private bool HasContradiction(List<List<String>> Sequences)
    {
        Cont = new List<Tuple<string, string>>();
        bool f = false;
        foreach (List<String> item1 in Sequences)
        {

            foreach (string elem1 in item1)
            {
                foreach (string elem2 in item1)
                {
                    int o1 = GetIndexOrder(item1, elem1, elem2);
                    foreach (List<String> item2 in Sequences)
                    {
                        int o2 = GetIndexOrder(item2, elem1, elem2);
                        if (o2 != 0 && o2 != o1)
                        {
                            Cont.Add(new Tuple<string, string>(String.Join(" ", item1), String.Join(" ", item2)));
                            f = true;
                        }
                    }
                }
            }
        }
        return f;
    }
    // this list stores contradicted pairs
    List<Tuple<string, string>> Cont = new List<Tuple<string, string>>();
    private int GetIndexOrder(List<string> item, string elem1, string elem2)
    {
        int i = item.FindIndex(x => x == elem1);
        int j = item.FindIndex(x => x == elem2);
        if (i < 0 || j < 0)
        {
            return 0;
        }
        if (i <= j)
        {
            return 1;
        }

        return 2;

    }

To test it:

    List<List<String>> seqs = new List<List<String>>{
    new List<String>{
        "1", "2", "3", "4", "5"
    },
    new List<String>{
         "2", "4", "5"
    },
    new List<String>{
        "2", "1","3","4","5"
    },
    new List<String>{
        "3", "2"
    },

};

        HasContradiction(seqs);
        foreach (var item in Cont.Distinct())
        {
            string tt = item.Item1 + "   AND  " + item.Item2;

            listView2.Items.Add(tt);
        }

Result:

Consider the case

A: 1 2 3 2 4 5
B: 1 2 2 4 5
C: 3 2
D: 2 3
E: 2 2
F: 1 2 3 4 5

You report back:

1 2 3 2 4 5 contradicts 3 2
1 2 3 2 4 5 contradicts 3 2
1 2 3 2 4 5 contradicts 3 2
1 2 3 2 4 5 contradicts 3 2
3 2 contradicts 1 2 3 2 4 5
3 2 contradicts 2 3
3 2 contradicts 1 2 3 4 5
3 2 contradicts 1 2 3 2 4 5
3 2 contradicts 2 3
3 2 contradicts 1 2 3 4 5
2 3 contradicts 3 2
2 3 contradicts 3 2
1 2 3 4 5 contradicts 3 2
1 2 3 4 5 contradicts 3 2

I used this code to test: ( http://goo.gl/QOEBao or http://www.tutorialspoint.com/compile_csharp_online.php?PID=0Bw_CjBb95KQMZGNRVXQ2Y0JlOU0 )

static void Main()
{
    List<List<String>> seqs = new List<List<String>>{
        new List<String>{
            "1", "2", "3", "2", "4", "5"
        },
        new List<String>{
            "1", "2", "2", "4", "5"
        },
        new List<String>{
            "3", "2"
        },
        new List<String>{
            "2", "3"
        },
        new List<String>{
            "2", "2"
        },
        new List<String>{
            "1", "2", "3", "4", "5"
        }
    };
    if (HasContradiction(seqs))
    {
        Console.WriteLine("yep");
        foreach(Tuple<string, string> x in Cont)
        {
            Console.WriteLine(x.Item1 + " contradicts "+ x.Item2);
        }
    } else {
        Console.WriteLine("nope");
    }
}

There's a few that are not correct - if I label them...

X 1 2 3 2 4 5 contradicts 3 2
X 1 2 3 2 4 5 contradicts 3 2
X 1 2 3 2 4 5 contradicts 3 2
X 1 2 3 2 4 5 contradicts 3 2
X 3 2 contradicts 1 2 3 2 4 5
Y 3 2 contradicts 2 3
Y 3 2 contradicts 1 2 3 4 5
X 3 2 contradicts 1 2 3 2 4 5
Y 3 2 contradicts 2 3
Y 3 2 contradicts 1 2 3 4 5
Y 2 3 contradicts 3 2
Y 2 3 contradicts 3 2
Y 1 2 3 4 5 contradicts 3 2
Y 1 2 3 4 5 contradicts 3 2

Then these are wrong:

X 1 2 3 2 4 5 contradicts 3 2
X 1 2 3 2 4 5 contradicts 3 2
X 1 2 3 2 4 5 contradicts 3 2
X 1 2 3 2 4 5 contradicts 3 2
X 3 2 contradicts 1 2 3 2 4 5
X 3 2 contradicts 1 2 3 2 4 5

Basically, what you don't do is check for duplicates.

Now, there's two things this could mean:

First option, you don't actually support duplicates. It's logically impossible for there to be duplicates. In that case, you should take an ordered, unique collection as input (a sorted set, as it were). A weaker alternative might be checking if you have duplicates and throwing errors for that, if altering the signature is not possible.

Second option, you do support duplicates. In that case, you should alter your code to support duplicates.


Simple factorial program using recursion Two concepts I realized I needed to understand and use more are recursion and Exceptions. Thus, I combined both in the following program. Although it began with a focus on using recursion it became more about Exceptions. I think the recursive part is bare-bones and straight-forward but I would nonetheless appreciate any tips/advice on using/formatting recursion in general.

On exception-handling: Is the following the optimal way of employing them or is there a more conventionally favored fashion? I get the feeling I may be missing doing something unnecessary or missing something important.

import javax.swing.JOptionPane;

class FactorialDemo {
    public static void main(String[] args) {
        int factorialNumber = 0;
        try {
            factorialNumber = Integer.parseInt(JOptionPane.showInputDialog(null,
                "Which number should we compute the factorial of?"));
        } catch(NumberFormatException nfe) {
            JOptionPane.showMessageDialog(null,"Input must be an integer!",
                "Error", JOptionPane.ERROR_MESSAGE);

            throw new NumberFormatException("Input must be an integer.");
        }

        JOptionPane.showMessageDialog(null,
                factorialNumber + " factorial is " +recur(factorialNumber) +".",
                "Result", JOptionPane.PLAIN_MESSAGE);
    }

    public static int recur(int n) {
        int result;
        if (n < 0) {
            JOptionPane.showMessageDialog(null,"n must be >= 0 but was " + n,
                "Error", JOptionPane.ERROR_MESSAGE);

            throw new IllegalArgumentException("n must be >= 0 but was " + n);
        }
        if (n < 2) {
            return 1;
        }

        result = recur(n - 1) * n;
        return result;
    }
}

Recursion

It's good that you are trying to grasp recursion, the more programming patterns you understand, the better.

But I would disagree that you need to use recursion more often. Generally, it consumes more memory and iterative solutions tend to be faster as well.

As for your solution, I think that if (n == 1) would be clearer than if (n < 2) (also, n < 2 returns 1 for input 0, which is wrong), and I wouldn't save the return value in result, but return it directly.

Exceptions

In recur throwing an IllegalArgumentException makes sense (it is an illegal argument), but showing the dialog here doesn't make that much sense, I would move that to main.

Also, don't throw an exception you just caught without a reason. If you don't want to execute the following function, just put all code in the try and catch the different exceptions.

Other

recur isn't a good name. I would call it factorial or factorialRecursive.
I would wrap the show message code into a function, that way you could also easily exchange it for something else (like a print). If you then further wrap this up in an object, unit testing would also be easier.

Code

If you do all of this, the code would look something like this:

public static void main(String[] args) {
    int factorialNumber = 0;
    try {
        factorialNumber = Integer.parseInt(input("Which number should we compute the factorial of?"));
        print(factorialNumber + " factorial is " + factorialRecursive(factorialNumber) + ".",
                "Result");
    } catch (NumberFormatException nfe) {
        error("Input must be an integer!", "Error");
    } catch (IllegalArgumentException iae) {
        error(iae.getMessage(), "Error");
    }
}

public static int factorialRecursive(int n) {
    if (n < 0) {
        throw new IllegalArgumentException("n must be >= 0 but was " + n);
    }
    if (n < 2) {
        return 1;
    }

    return factorialRecursive(n - 1) * n;
}

public static String input(String message) {
    return JOptionPane.showInputDialog(null, message);
}

public static void print(String message, String title) {
    JOptionPane.showMessageDialog(null,
            message,
            title, JOptionPane.PLAIN_MESSAGE);
}

public static void error(String message, String title) {
    JOptionPane.showMessageDialog(null, message,
            title, JOptionPane.ERROR_MESSAGE);
}


Extracting website names from link code cleanup I'm working on a program that takes website links and extracts the website name. Right now, it works perfectly, but it is very much a brute force approach and very ugly in my opinion.

Some of the properties of the links are as follows:
- entirely random
- will all contain https:// and .com
- may not contain www.

Here's a random link that I pulled up while shopping to give an example of what I'm talking about. Just to be 100% clear.

https://www.walmart.com/ip/Glencairn-Crystal-Whiskey-Glass-Set-of-2-Hailed-as-The-Official-Whiskey-Glass/183116827

remove 'https://www.'
remove '.com/....827'

result = walmart

And here is the code for it all:

f = open("Links.txt").read().split("\n")
f.remove('')

results = []

for i in f:
    if 'https://' in i:
        results.append(i[8:])

f = results
results = [f[0]]

for i in f:
    if 'www.' in i:
        results.append(i[4:])

f = results
results = []

for i in f:
    results.append(i[:i.find('.com')])

f = open("Results.txt", 'w')

for i in results:
    f.write(i + "\n")

f.close()

I tried cleaning it up with the re module, but it was throwing some errors when trying to search using re.search('www.(.*).com', f).

I was thinking about using the [a:] through [:b] notation in python, but since each link may not have 'www.' it seemed like it would be a faulty solution.

As I mentioned, this code works perfectly well. It's just such a simple thing that I want to get some practice in computer science and make it look like an elegant-ish solution.

As mentioned in the answer by Roland Illig, there is a module for that.

Example:

from urllib.parse import urlparse

def get_domain_name(url: str) -> str:
    """Return domain name from URL
    """
    parsed_uri = urlparse(url)
    return parsed_uri.hostname

get_domain_name('https://www.ucl.ac.uk/alumni/services')

Result:

'www.ucl.ac.uk'

NB: this requires a full URL with http/https scheme.

Third-level domain extensions are handled with no problems. This is the prefered approach. The Python philosophy is that there should be one obvious way of accomplishing a given task. It doesn't have to be more complicated.

if you know all domain names will end in .com and want to get rid of it, just add .replace('.com', '').

A regular expression can also get the job done. Something like this will return walmart:

^https://(?:www\.)?([a-z0-9_\-]+)\.com

Assuming that the URL always starts with https://, and the domain name ends in .com, with www. optional and not included in the capture group.

To explain this bit: (?:www\.)?
The rightmost question mark means the expression in parentheses is optional. ?: means: match the expression but do not capture it.

This is not an all-purpose expression, it is adjusted to your circumstances and should be good enough for your needs but that's it.

Let's say you have more complicated cases with subdomains, as an example:

url = 'www.subdomain.walmart.com'

Once you've got the full domain name, you could do some splitting then extract the relevant portions starting from the right, knowing that .com will be the last element:

bits=url.split('.')
print(bits)
['www', 'subdomain', 'walmart', 'com']
print(bits[-2])
walmart

I think this is slightly more flexible than working with fixed lengths like you're doing.

As for reading/writing files have a look at context managers (using the with statement).

Your code is not very long but you would still benefit by keeping the parsing in one dedicated function (possibly two), out of your loop. That would make the whole code easier to read and maintain.

One remark regarding www.: at some point you will find that some sites do redirect to ww1 or ww2 or stuff like that. Not to mention other types of subdomains. It is not safe to assume that the domain name will always be prefixed with www. or nothing.


Lagrange Interpolation over quadrilateral points I've been working on a program which calculates, given a point and 4 surrounding points, the Lagrange polynomial, in order to interpolate a value. Consider that I'm not a mathematician and I better understand code than formulas.

I've came up with the following code, which works, but I really don't think is general (and it's pretty ugly to me).

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

namespace LagrangeInterpolation
{
    public class Point : ICloneable
    {
        public double X { get; set; }

        public double Y { get; set; }

        public double Value { get; set; }

        public Point Clone()
        {
            return (Point)this.MemberwiseClone();
        }
    }

    public static class Lagrange
    {
        public static Point Interpolate(Point[] controlPoints, Point point)
        {
            var A = -controlPoints[0].X - controlPoints[1].X + controlPoints[2].X + controlPoints[3].X;
            var B = -controlPoints[0].X + controlPoints[1].X + controlPoints[2].X - controlPoints[3].X;
            var C = +controlPoints[0].X - controlPoints[1].X + controlPoints[2].X - controlPoints[3].X;
            var X = 4 * point.X - controlPoints.Sum(x => x.X);

            var D = -controlPoints[0].Y - controlPoints[1].Y + controlPoints[2].Y + controlPoints[3].Y;
            var E = -controlPoints[0].Y + controlPoints[1].Y + controlPoints[2].Y - controlPoints[3].Y;
            var F = +controlPoints[0].Y - controlPoints[1].Y + controlPoints[2].Y - controlPoints[3].Y;
            var Y = 4 * point.Y - controlPoints.Sum(x => x.Y);

            var r = (X / 4 - B * Y / 4 * E) / (1 - D / 4 * E);
            var s = (Y - D * r) / E;

            var prevR = 0d;
            var prevS = 0d;
            const double precision = 0.00000001;
            while (!(prevR - r < precision && prevS - s < precision))
            {
                prevR = r;
                prevS = s;
                r = (X - B * s) / (A + C * s);
                s = (Y - D * r) / (E + F * r);
            }

            // Interpolate value
            var result = point.Clone();
            result.Value = ((1 - r) * (1 - s) * controlPoints[0].Value + (1 - r) * (1 + s) * controlPoints[1].Value + (1 + r) * (1 + s) * controlPoints[2].Value + (1 + r) * (1 - s) * controlPoints[3].Value) / 4;

            return result;
        }
    }
}

The input parameters are:

controlPoints: the 4 points, each one with its Value.
point: the point for which we want to calculate the interpolated value

The returned Point is a clone of the Input point with the Value property set.
Every instance of Point have X and Y normalised within range -1..1 (I subtract the quadrilateral center from each point).

Example:

controlPoints = new [] {
    new Point() { X = -0.033675000000000566, Y = -0.02564999999999884, Value = 1.2787 },
    new Point() { X = -0.035524999999999807, Y = 0.024329999999999075, Value = 1.329 },
    new Point() { X = 0.03370499999999943, Y = 0.02564999999999884, Value = 1.3376 },
    new Point() { X = 0.035494999999999166, Y = -0.024329999999999075, Value = 1.302 }
}

point = new Point() { X = 0.018148174616284152, Y = -0.014201699949808244 }

Expected result is Point.Value = 1.3044829106888913

Can someone suggest a better way (formally and mathematically) to perform this calculation?

I would use a struct with copy constructor instead of a class with clone. Performance wise it would be better and would be more readable.

Extract function for your condition in the while.

Add explicit parenthesis on complex arithmetic expressions (normal people don’t read operator precedence fluently). ( I think about this part B * Y / 4 )

Seems like you do six times the same thing with your points. Extract method somehow and name it appropriately (cross or whatever it is).