moving player right or left depending on swipe In my Player.java class, I want to incorporate a function that moves my player according to the left or right swipes. I also used time in seconds in order to vary the movement in an cyclic way:

'''
class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-4:00"));
            Date currentLocalTime = cal.getTime();
            DateFormat date = new SimpleDateFormat("KK:mm");
            date.setTimeZone(TimeZone.getTimeZone("GMT-4:00"));
            String localTime = date.format(currentLocalTime);
            try {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    X-=K;
                    int currentSeconds = cal.get(Calendar.SECOND);
                    Y=Y*Math.cos(18.currentSeconds);
                } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    X+=K;
                    int currentSeconds = cal.get(Calendar.SECOND);
                    Y=Y*Math.cos(18.currentSeconds);
                }
            } catch (Exception e) {
                // nothing
            }
            return false;
        }
'''

After some research, this is the class I included in player.java. So my question is: Is there a more efficient way to detect swiping directions(without creating any additional class) and what is your opinion about the code structure knowing that the objective is to change X according to swipe direction.

Thank you.

I changed some local variables and make them static variables, why ? because these are created and destroyed if you use serveral times the method onFling. The main Idea is to improve the performance and decrease the space your method uses.

Also I refactorized some pieces of code

class MyGestureDetector extends SimpleOnGestureListener {
        private static DateFormat date = new SimpleDateFormat("KK:mm");
        private static Calendar cal;

        MyGestureDetector() {
            date.setTimeZone(TimeZone.getTimeZone("GMT-4:00"));
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-4:00"));
            String localTime = date.format(cal.getTime());
            try {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    X -= K;
                    Y *= Math.cos(18*cal.get(Calendar.SECOND)); //18 * currentSeconds i think
                } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    X += K;
                    Y *= Math.cos(18*cal.get(Calendar.SECOND));
                }
            } catch (Exception e) {
                // Perhaps if the program does nothing or have an unexpected behavior
                // you are silencing the cause (it has happened to me)
                e.printStackTrace();
            }
            return false;
        }

Hope it helped.


Combat game - character factory I decided to improve my OOP design knowledge and learn python at the same time so I started to write a simple program which will be a fight "simulator".

For now, there are only 2 character types : Orc and Human.
The CharacterFactory class is created so that I'll be able to handle Orc and Human classes in a more abstract way or so.

GameState is meant to track the state of the game. Instances will be immediately registered to the GameState as soon as they created. And for example, if a character dies, I want to remove it from the list as well. (self.characters).

    #abtract factory or something
class CharacterFactory:
    def __init__(self, character=None, game_state=None):
        self.character = character
        game_state.register_character(self)

    def inspect(self):
        print(self.character.name)
        print(self.character.attack_dmg)
        print(self.character.health)
        print("\n")

    def attack(self, target):
        target.character.health = target.character.health - self.character.attack_dmg

#Observable or so
class GameState:
    def __init__(self):
        self.characters = []

    def register_character(self, character):
        self.characters.append(character)

    def show_characters(self):
        list(map(lambda x: x.inspect(), self.characters))

class Orc:
    def __init__(self,name):
        self.name = name
        self.attack_dmg = 50
        self.health = 100

class Human:
    def __init__(self,name):
        self.name = name
        self.attack_dmg = 45
        self.health = 105

def Main():
    game_state = GameState()

    orc = CharacterFactory(Orc("Karcsi"),game_state)
    #orc.inspect()
    #orc.attack()

    human = CharacterFactory(Human("Nojbejtoo"),game_state)
    #human.inspect()
    #human.attack()

    print("Game state:\n")

    game_state.show_characters()

    orc.attack(human)

    game_state.show_characters()

Main()

My question is:

Is this a good design? Or maybe a complete pain in the ... to work with? Is there something that I could improve?

Of course this code is really far from being finished, but I try to find the best approach possible to design things like this so that i can deepen my knowledge in design patterns and stuff like that.

The CharacterFactory class is created so that I'll be able to handle Orc and Human classes in a more abstract way or so.

You try to stay DRY which is very good, but this idea would be better represented with inheritance.

You could create a class Character() and let both Human and Orc, inherit from the super class like so:

class Character():
    def __init__(self, health, attack_damage, name):
        self.attack_damage = attack_damage
        self.health = health
        self.name = name

    def attack(self, target):
        target.health -= self.attack_damage

    def __str__(self):
        return f"Name: {self.name}\nDamage: {self.attack_damage}\nHealth: {self.health}\n"

class Human(Character):
    def __init__(self, name, health=105, attack_damage=45):
        super().__init__(health, attack_damage, name)

class Orc(Character):
    def __init__(self, name, health=100, attack_damage=50):
        super().__init__(health, attack_damage, name)

def main():
    orc = Orc("Karcsi")
    human = Human("Nojbejtoo")

    print(orc)
    print(human)

    orc.attack(human)
    print(human)

if __name__ == "__main__":
    main()

Things I changed:

Instead of an inspect function, I override the magic function __str__ so you can directly print(human) or print(orc)
The use of the if __name__ == '__main__'
And the snake_case functions main instead of Main
In the attack function body, see how a = a - b equals a -= b

I have omitted the GameState part, maybe someone else will pick that up.

Good luck with your game!


Find closest greater and smaller number from a sorted array I have a sorted array. It can be empty. I have to find its closest greater and smaller number. If the given number is present in the array, it will be considered as greater number. I implemented it like the below style. But I am not satisfied with my approach. Can anyone suggest better ways?

findPreviousNext(array:number[], currentValue: number): ClosestValues
{
    let immediateNextIndex = -1;
    var closestvalues = new ClosestValues();
    for (let i = 0; i < array.length; i++) {
        if (array[i] >= currentValue) {
            immediateNextIndex = i;
            break;
        }
    }
    switch (immediateNextIndex) {
        case 0: {
            closestvalues.immediateNext = array[immediateNextIndex];
            closestvalues.immediatePrevious = null;
            break;
        }
        case -1: {
            var prevVal = array[array.length -1];
            closestvalues.immediateNext = null;
            closestvalues.immediatePrevious = (prevVal != null && prevVal != undefined) ? prevVal : null;
            break;
        }
        default: {
            let prevVal = array[immediateNextIndex - 1];
            closestvalues.immediateNext = array[immediateNextIndex];
            closestvalues.immediatePrevious = (prevVal != null && prevVal != undefined) ? prevVal : null;
        }
}

return closestvalues;
}

First of all, comments would be nice. Speaking in terms of implementation rarely helps another person understand what the code is doing. Especially when the code uses very generic variable names. My general rule to comments is when the code tries to do something clever, write a comment.

You could short-circuit the logic if the array is empty. No sense having the code run if you know ahead of time it does nothing.

Also, by eliminating cases early, you can start making assumptions. This would allow you to simplify logic or make optimizations to existing logic, turning general-case logic to case-specific logic.

for (let i = 0; i < array.length; i++) {
    if (array[i] >= currentValue) {
        immediateNextIndex = i;
        break;
    }
}

Could be simplified using array.findIndex.

Here's my take on it:

const findPreviousNext = (array, currentValue) => {
  // Short-circuit the code if the array is empty.
  if(array.length === 0){
    return { next: null, prev: null }
  }

  // Find the index of the closest greater number.
  const closestIndex = array.findIndex(v => v >= currentValue)

  // A non-existent/negative index is undefined. No need for extensive checks.
  const closestNext = array[closestIndex] || null
  const closestPrev = array[closestIndex - 1] || null
  const lastValue = array[array.length - 1] || null

  // The only special case is the non-existent value (index = -1)
  const next = closestIndex === -1 ? null : closestNext
  const prev = closestIndex === -1 ? lastValue : closestPrev

  // Build the instance (a simple POJO in this case).
  return { next, prev }
}

console.log(findPreviousNext([], 3))
console.log(findPreviousNext([1], 3))
console.log(findPreviousNext([1, 2], 3))
console.log(findPreviousNext([1, 2, 3], 3))
console.log(findPreviousNext([1, 2, 3, 4], 3))


php most elegant function call returning array I am asking your preference between two similar solutions.

First way :

public function test($myvar) {

    switch ($myvar) {
        case 'test1': return [
                          'value' => 'Value of test1',
                          'short' => 'Val 1'
                      ];
        break;
     }
}

$this->test('test1')['short']  // Val 1

Second way:

public function test($myvar, $key) {

    switch ($myvar) {
        case 'test1': $array = [
                          'value' => 'Value of test1',
                          'short' => 'Val 1'
                      ];
    }

    return $array[$key];
}

$this->test('test1', 'short')  // Val 1

Even if both function return same value, what is the most elegant and readable way for you guys ?

This question is not simply preference, the second method is better than the first for the following reasons:

In the first, you initialise a function test and it returns an array: test[]
So, alongside the string to test against 'short' in the memory, you now have those three things in the memory.

Whereas, in the second example, you don't return an array, and the 'short' string is only used as a parameter, by doing this you now can only have two things in the memory.

Therefore, the second code block is better than the first.

Also, in the spirit of Code Review, you can further improve the second code block, by not actually assigning $array, or using a switch.

public function test($myVar, $key) {
    return [
        'test1' => [
            'value' => 'Value of test1',
            'short' => 'Val 1'
        ]
    ][$myVar][$key];
}

$this->test('test1', 'short')  // Val 1

$myvar should also be in camelCase: $myVar


Fast Factorisation (Python Implementation) An algorithm for finding prime factors of a number given a list of all primes up to the square root of the number. It's worst case time complexity is \$O(n^{1/2})\$, the best case would be \$O(\log(n))\$, and I don't know how to calculate average case or amortised worst case. I am aware that this is not strictly optimal, but I think it is easier to understand and implement, than say Pollard's rho algorithm for prime factorisation (I suspect it works better if the number is composite with many prime factors as well). Suggestions for improvements are welcome.

FastFactorise.py

def fact(n):
    """
        *   Function to factorise a given number given a list of prime numbers up to the square root of the number.

        *   Parameters:
            *   `n`: The number to be factorised.
        *   Return:
            *   `res`: A dict mapping each factor to its power in the prime factorisation of the number.
        *   Algorithm:
            *   Step 1: Initialise `res` to an empty dictionary.
            *   Step 2: If `n` > 1.
            *   Step 3: Iterate through the prime number list.
            *   Step 4: If ever the current prime number is > the floor of the square root of `n` + 1 exit the loop.
            *   Step 5: If the current prime number is a factor of `n`.
            *   Step 6: Assign 0 to `e`.
            *   Step 7: While the current prime number is a factor of `n`.
            *   Step 8: Increment `e`.
            *   Step 9: Divide `n` by the current prime number.
            *   [End of Step 7 while loop.]
            *   Step 10: Map the current prime number to `e` in the result dictionary.
            *   [End of step 5 if block.]
            *   Step 11: If `n` is not 1 (after the repeated dividings) map `n` to 1 in the result dictionary.
            *   Step 12: Return the result dictionary.
            *   [Exit the function.]
    """
    res = {}
    if n > 1:
        for p in primes:
            if p > int(sqrt(n)) + 1:    break
            if n%p == 0:
                e = 0
                while n%p == 0:
                    e += 1
                    n //= p
                res[p] = e
        if n != 1:      res[n] = 1
    return res

sqrt is expensive.  You can avoid it by reworking your test condition from:

p > int(sqrt(n)) + 1

to:

p*p > n

You can skip one while n%p == 0 iteration by initializing e = 1 and unconditionally dividing by p once you’ve found a prime factor:

if n%p == 0:
    e = 1
    n //= p
    while n%p == 0:
        # ...etc...

Avoid putting “then” statements on the same line as  the if statement:  place the “then” statement indented on the next line.

The algorithm should be a comment, not part of the """docstring"""; callers generally only care about how to use the function, not the implementation details.


Generate another random path through a complete graph What this does is generate a random path of cities to later calculate the length of the newly generated tour of cities, the TSP.

I am trying to figure out if there is a more efficient way to write this algorithm. I have tried using the std::shuffle and std::random_shuffle but did not notice any improvement in the run time. Any other resources I should try taking a look at?

std::vector<City> GetRandomPath(std::vector<City> oldPath)
{
    std::vector<City> newPath;

    newPath = oldPath;

    int randPoint = rand() % (oldPath.size()-1);
    int randPoint2 = rand() % (oldPath.size()-1 - randPoint) + randPoint;

    int k=1;
    for(int i =0; i < randPoint; i++)
    {
        newPath.push_back(oldPath.at(i));
    }
    for(int i=randPoint; i < randPoint2; i++)
    {

        newPath.push_back(oldPath.at(randPoint2-k));
        k++;
    }
    for(int i=randPoint2; i < oldPath.size(); i++)
    {
        newPath.push_back(oldPath.at(i));
    }

    return newPath;
}

From your code I'm guessing that you're doing some 2-opt for the TSP. And yes, it is possible to make it faster. The secret actually lies within your code, and is also the reason why your code isn't working.

Disclaimer: I am no expert at C++

When you do newPath = oldPath, you're making newPath a vector that is identical to, but not the same as oldPath. Then you push all elements from oldPath onto newPath, thus making it twice as big as oldPath.

But since you already have a concise way of copying all values to a new vector, let's use that to speed things up:

std::vector<City> GetRandomPathFast(std::vector<City> oldPath)
{
    std::vector<City> newPath = oldPath;

    int randPoint = rand() % (oldPath.size()-1);
    int randPoint2 = rand() % (oldPath.size()-1 - randPoint) + randPoint;

    int k = 1;
    for(int i=randPoint; i < randPoint2; i++)
    {
        newPath[i] = oldPath[randPoint2-k];
        k++;
    }
    return newPath;
}

By only modifying the values between randPoint and randPoint2, we get a significant speedup. We also get a path of the correct length, with a part of it reversed.

For benchmarking, I changed both your function and my new to use std::vector<int>, but numbers should carry over to your implementation.

Vector of length 1000, 10000 iterations of each function:
Time for GetRandomPath: 280.624 ms
Time for GetRandomPathFast: 22.136 ms


Check type of executable file I write this program that checks if a file is executable, and if so, to check if it is an ELF binary or a shell script.
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>

int Search_in_File(char *fname, char *str);

int main(int argc, char **argv)
{
    if(argc < 2){
        printf("The path to the file is\n");
        return 1;
    }

    struct stat fileStat;

    if(stat(argv[1],&fileStat) < 0){
        printf("error\n");
        return 1;
    }

    if(S_ISREG(fileStat.st_mode)){
        if(fileStat.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
        {
            printf("The file is executable ");
            Search_in_File(argv[1], "#!");
            Search_in_File(argv[1], "ELF");
        }
        else
        {
            printf("The file is not executable.\n");
        }
    }
    else
        printf("Not a file\n");
    return 0;
}

int Search_in_File(char *fname, char *str) {
    FILE *fp;
    char temp[512];

    if((fp = fopen(fname, "r")) == NULL) {
        return(-1);
    }

    while(fgets(temp, 512, fp) != NULL) {
        if((strstr(temp, str)) != NULL) {
            if(strcmp(str, "#!")==0)
                printf("shell type.");
            else if(strcmp(str, "ELF")==0)
                printf(" ELF.");
        }
    }
    printf("\n");
    if(fp) {
        fclose(fp);
    }
    return(0);
}

if(argc < 2){
    printf("The path to the file is\n");
    return 1;
}

The error message is unfinished (appropriately enough, missing is missing), and it should go to stderr, not stdout.

if(stat(argv[1],&fileStat) < 0){
    printf("error\n");
    return 1;
}

Again we're writing to the wrong stream.  And we could make a more informative message, e.g. perror(argv[1]).

        Search_in_File(argv[1], "#!");
        Search_in_File(argv[1], "ELF");

These two calls each open the file to read it.  It is probably better to open the file just once.  Why do we ignore the return value each time?

while(fgets(temp, 512, fp) != NULL) {
    if((strstr(temp, str)) != NULL) {
        ⋮
    }
}

This code will fail to match when the search string straddles a 512-byte boundary.  But why are we searching the whole file anyway?  Those magic strings are only meaningful as the first characters, and do not tell us anything if they occur later in the file.  We could do this much more simply:
if (fread(temp, 4, 1, fp) == 1
    && strncmp(temp, str, strlen(str)) == 0) {
    ⋮
}

        if(strcmp(str, "#!")==0)
            printf("shell type.");
        else if(strcmp(str, "ELF")==0)
            printf(" ELF.");

Instead of string-matching the str argument, why not just pass an additional argument specifying the string to print?  Then there's only one place to modify when you add a new test.

if(fp) {
    fclose(fp);
}

At this point, we know that fp is non-null, since we already returned if it isn't.
Oh, and an executable that begins with #! could be any type of interpreted executable (e.g. Python or Sed script), not necessarily a shell script.  Not sure whether that's what's intended (is it your description or the program that needs adjusting?).


Program to print the number as a sum of consecutives We need the input number as the sum of consecutive natural numbers.

  Examples:

  For input 27, output should be:

  2 3 4 5 6 7

  8 9 10

  13 14

  For input 9, the output should be:

  4 5

  2 3 4

Here is my code. It works as it is expected to:

import java.util.*;
class Consecutives
{
    static void print()
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number: ");
        double n = sc.nextDouble();
        /*
         * Needed: Different Arithmetic progressions (APs) with common difference 1;
         * i(2a + (i-1)) = 2n // from formula for sum of AP, a indicates first term of progression
         * #implies -> a = n/i - (i-1)/2   // i indicates number of terms of AP possible
         * Now, a can't be negative so:
         * -> n/i > (i-1)/2
         * -> Range of i = [2, (int)(1+sqrt(1+8n))/2]
         */
        int max_i = (int)((1+Math.sqrt(1+8*n))/2);
        System.out.println("Max i = "+ max_i);
        double a;
        for(double i=2; i <= max_i ;i++)
        {
            a = n/i - (i-1)/2;
            if(a == Math.floor(a) && a>0)//i.e if a is an integer
            {

                if(i*(2*a+ (i-1))== 2*n)
                {
                    for(int j= (int)a ; j<=a + (i-1) ;j++)
                        System.out.print(j+ " ");
                    System.out.println();
                }
                else
                    break;
            }

        }
    }
}

Are my comments too messy? Is there any way to change them and still make the logic clear to the reader? What other improvements can I make to my program?

Your algorithm, being \$O(\sqrt n)\$, is pretty efficient.  I just think that your code could just a bit of cleanup.

Your print() function does all kinds of things, mostly unrelated to printing.  You should separate the code for the user interaction from the calculation.  (Since each result is a pair of numbers, and there will be an indeterminate number of results, I'd use a callback.)  You should also extract the loop the prints each series into a helper function.  (Executing many System.out.print() statements can be surprisingly slow, as each one is a separate I/O operation.)

Your mathematical reasoning was not clear to me at first.  I would have preferred a comment that more clearly explained the nomenclature and used fewer words.

// n = a + (a+1) + ... + (a+i-1) (Given n, find all a>0 and i>=2)
//
// 2n = i(2a + (i-1))            (arithmetic series formula)
//
// a = (2n - i(i-1)) / 2i
//
// 2n > i(i-1)                   (because a>0 and i>0)
//
// 2 <= i < (1+sqrt(1+8n))/2     (quadratic formula)

Since this is supposed to be an exercise in integer arithmetic, you should avoid using doubles.  Use either int or long.  Note that I have avoided your a = n/i - (i-1)/2, which involves non-integer division.

Actually, you don't need to calculate max_i.  You don't really trust that bound, and you test for a > 0 anyway.

Suggested solution

import java.util.Scanner;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

public class Consecutives {
    /**
     * Find integers a>0 and i>=2 such that n = a + (a+1) + ... + (a+i-1).
     *
     * @param n        The target sum.
     * @param callback A function that will be called with parameters a and i
     *                 for each solution found.
     */
    public static void findSeries(long n, BiConsumer<Long, Long> callback) {
        // n = a + (a+1) + ... + (a+i-1) (Given n, find all a>0 and i>=2)
        //
        // 2n = i(2a + (i-1))            (arithmetic series formula)
        //
        // a = (2n - i(i-1)) / 2i

        for (long i = 2; ; i++) {
            long aNumer = 2 * n - i * (i - 1);
            long aDenom = 2 * i;
            if (aNumer <= 0) break;
            if (aNumer % aDenom == 0) {
                callback.accept(aNumer / aDenom, i);
            }
        }
    }

    /**
     * Form a string of all integers in the range [a, a+i), separated by space.
     */
    private static String spaceDelimitedRange(long a, long i) {
        return LongStream.range(a, a+i)
                         .mapToObj(String::valueOf)
                         .collect(Collectors.joining(" "));
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter number: ");
        findSeries(
            scanner.nextLong(),
            (a, i) -> System.out.println(spaceDelimitedRange(a, i))
        );
    }
}


Return nil after loop and also in unless block in Ruby I have a working code as below. Is there any better way to return nil after the each loop and unless else in the below example?
def find_member(member_name)
  unless members.empty?
    members.each do |member|
      if member.name == member_name
        return member
      end
    end
    nil
  else
    nil
  end
end

I should pass nil in each case because there are different conditions in other methods where this method is called. That is the reason why I have written the code as above.

Ruby has a detect method, so your entire method can be replaced with
members.detect { |member| member.name == member_name }

As an aside, each works fine for empty arrays, hence the empty? check you have is completely unnecessary even if you keep the explicit loop.


Duplicate the previous input if zero or not a number I have the following code which  duplicates the previous input if any entry is less than zero or NaN, except the first row of a matrix.

Is there any other efficient way to do this without using multiple for loops? The input matrix values may differ in some case and may contain float values or alphabets. The matrix considered here is just an example. The actual table will be 14352 x 42 in shape.

import numpy as np

data = [[0, -1, 2],
        [7, 8.1, -3],
        [-8, 5, -1],
        ['N', 7, -1]]
m, n = np.shape(data)

for i in range(1, m):
    for j in range(n):
        if data[i][j] < 0 or not isinstance(data[i][j], (int, float,long)):
            data[i][j] = data[i-1][j]

The output is:

[[0,-1,2],
 [7,8.1,2],
 [7,5,2],
 [7,7,2]]

It's possible to solve this problem using a functional Pythonic approach a layer at a time.

First, the original code is refactored as functions for reference. Long type and numpy were not available on my current workstation but were not necessary to process the example data.
A transpose and substituting generator are used to produce an alternative proof of concept. It is elaborated to include a "first qualified value or default to 0" rule because the original algorithm did not clean the first row and propagates unqualified values in a column until a qualified value occurs.

I've included a demo at the end that shows why a list comprehension fails since It does not alter the table in place.

#original code refactored as functions
data = [[0, -1, 2], [7, 8.1, -3], [-8, 5, -1], ['N', 7, -1]]
print("data: ", data)
def unnumeric_or_neg(z):
    return not isinstance(z, (int, float)) or z < 0

def clean1 (data,unqal):
    m, n = 4,3
    for i in range(1, m):
        for j in range(n):
            if unqal(data[i][j]) :
                data[i][j] = data[i-1][j]
clean1(data,unnumeric_or_neg)
print("result is in data", data)
#refresh data
data = [[0, -1, 2], [7, 8.1, -3], [-8, 5, -1], ['N', 7, -1]]
#help functions and another approach
def comp_transpose(t):
    "transpostion of rectangular table"
    return [[r[j] for r in t] for j,_ in enumerate(t[0])]

def sub_last_qal(lst,unqal):
    last_qual=0
    for (n,x) in enumerate(lst):
        if unqal(x):
            yield last_qual
        else:
            last_qual = x
            yield x
def clean2(data,unqal):
    data_t = comp_transpose(data)
    data_aug = [list(sub_last_qal(col,unqal)) for col in data_t]
    return [data[0],]+comp_transpose(data_aug)[1:]
print("2 step similar result",clean2(data,unnumeric_or_neg))
def first_qal(lst,unqal):
    """given a list return the first qualifying value given
    negative test unqal is set in scope"""
    for x in lst:
        if not unqal(x):
            return x
    return 0
def clean3(data,unqal):
    data_t = comp_transpose(data)
    data_aug = [list(sub_last_qal([first_qal(col,unqal),]+col,unqal)) for col in data_t]
    return comp_transpose(data_aug)[1:]
cn3 = clean3(data,unnumeric_or_neg)
print("augmented first qual rule ",cn3)

def first_qal_row(data_c,unqual):
    return [ first_qal(vlist,unqual) for vlist in comp_transpose(data_c)]

#list comprehensions do not support back references to results
def not_clean(data,unqal):
    return [data[0],]+[[(data[i-1][j] if unqal(x) else x ) \
        for (i,x) in enumerate(y)] for (j,y) in enumerate(data[1:])]
cn = not_clean(data,unnumeric_or_neg)
print("result is unclean", cn)
print("data is not changed ", data == [[0, -1, 2], [7, 8.1, -3], [-8, 5, -1], ['N', 7, -1]])

Output:

data:  [[0, -1, 2], [7, 8.1, -3], [-8, 5, -1], ['N', 7, -1]]
result is in data [[0, -1, 2], [7, 8.1, 2], [7, 5, 2], [7, 7, 2]]
2 step similar result [[0, -1, 2], [7, 8.1, 2], [7, 5, 2], [7, 7, 2]]
augmented first qual rule  [[0, 8.1, 2], [7, 8.1, 2], [7, 5, 2], [7, 7, 2]]
result is unclean [[0, -1, 2], [7, 8.1, 7], [7, 5, 8.1], [-1, 7, -3]]
data is not changed  True


Immutable subclass of a Set class If I'm creating an immutable class from an existing class, should I override methods that mutate the property or have an instance of it and write my own methods to read from the property?

I have an existing class Set which is basically a fancy array. There's a few more methods in the class but for the purposes of this question they aren't relevant.

<?php

class Set implements \ArrayAccess, \Countable, \IteratorAggregate
{
    protected $items;

    public function __construct(array $items = array()) {
        $this->items = $items;
    }

    public function has($key) {
        return array_key_exists($key, $this->items);
    }

    public function get($key) {
        return $this->has($key) ? $this->items[$key] : null;
    }

    public function set($key, $value) {
        $this->items[$key] = $value;
    }

    public function remove($key) {
        unset($this->items[$key]);
    }

    public function count() {
        return sizeof($this->items);
    }

    public function offsetExists($offset) { return $this->has($offset); }
    public function offsetGet($offset) { return $this->get($offset); }
    public function offsetSet($offset, $value) { $this->set($offset, $value); }
    public function offsetUnset($offset) { $this->remove($offset); }

    public function getIterator() {
        return new \ArrayIterator($this->items);
    }
}

Now I want to create ImmutableSet and here are two options that I came up with:

class ImmutableSet extends Set
{
    public function set($key, $value) {
        throw new \Exception('Cannot set things');
    }

    public function remove($key) {
        throw new \Exception('Cannot remove things');
    }
}

The problem I see with this approach is the existence of set and remove for an immutable object doesn't seem right and supposing that the Set class implemented a method for example clear then I'd have to override that too.

Alternatively, I can do this:

class ImmutableSet implements \Countable, \IteratorAggregate
{
    private $items;

    public function __construct(array $items) {
        $this->items = new Set($items);
    }

    public function has($key) {
        return $items->has($key);
    }

    // Implement get, count, and getIterator to call $items->
}

My concern with this design is basically the opposite of the other one. Supposing that Set implemented a method getAllKeys, I'd have to implement it here too to benefit from the functionality.

What is the better approach here?

You are right it seems rather weird for an immutable object to provide setters, which will throw an exception no matter how you call it. I would use inheritance and two different interfaces in this situation.

Imagine the base set. I would argue the base class should be the immutable set, since the immutable set declares functionality which both classes should be able to use. An example could be:

interface ImmutableInterface {

    public function fetch($key);
    public function exists($key);

}

class ImmutableSet implements ImmutableInterface {

    protected $items = [];

    public function __construct(array $items)
    {
        $this->items = $items;
    }

    public function fetch($key)
    {
        return $this->items[$key];
    }

    public function exists($key)
    {
        return array_key_exists($key, $this->items);
    }

}

You now have a basic implementation. You make your set manipulatable you could write a new interface declaring methods for changing values inside your set. The new interface could be:

interface ChangeableInterface {

    public function add($key, $value);

}

You could then write a sub-class of your original immutable set and implement the new interface. Since the $items array was declared protected any sub-class also has access to it.

class ChangeableSet extends ImmutableSet implements ChangeableInterface {

    public function add($key, $value)
    {
        $this->items[$key] = $value;
    }

}

You can now type-hint against a specific required implementation by using the interfaces. You also have the opportunity to use other classes as long as they implement the specific interface.

You can think of this strategy as declaring the fewest amount of required methods for your class to work. If you want to add more functionality you write an interface declaring no more than the required methods for that functionality to work. You can even take this further. Imagine not all your changeable sets should be able to remove items again. This could be an interface:

interface RemoveableInterface {

    public function remove($key);

}

You would then write a new sub-class of either the ChangeableSet or ImmutableSet, depending on your requirements, and implement the new interface. You can now type-hint specifically against sets which are only able to remove items. This strategy can continue forever, but do be careful. This can also be too much. Too many sub-classes can become a hell to maintain. So try to keep the amount of interfaces low, while still maintaining your required flexibility and the method signatures they declare concise.

The interface/class names used in these examples are not set in stone. They are by purpose very descriptive, so you can always rename them. Also keep in mind  there are no error checking in the examples.

I hope this can help you, happy coding!


Multiple list comparison Python I have some code that has three lists, and it then checks the index of the second list against the index of the first as long as the first list has six elements. The code will then append to the third list if part of a string matches in the index of the first list. If the string does not match, it will append a message. I am hoping to find a better, more Pythonic way of writing my algorithm. Here is my code:
L1 = ["first = 1st","second = 2nd","third = 3rd","fourth = 4th","sixth = 6th",
  "first = A","second = B","third = C","fifth = E","sixth = F",
  "second = W","third = X","fourth = Y","fifth = Z","sixth = AA","first = BB"]
L2 = ["first","second","third","fourth","fifth","sixth"]
L3 = []

#Used in case a list has less than six elements
if len(L1) % 6 != 0:
    L1.append("Missing_Data")

c = 0
for i in L1:
    cont = True
    while cont:
        if L2[c] in i:
            L3.append(i.split("= ")[-1])
            c += 1
            if c < len(L2):
                cont = False
            else:
                c = 0
                cont = False
        else:
            L3.append("Missing_Data")
            c += 1
            if c < len(L2):
                continue
            else:
                c = 0
                break

This code works for what I want it to do but I think its too long. Any help in making this code more Pythonic would be greatly appreciated. Thanks in advance.

My review of your current code is easy to summarize: It's too darn complicated and
makes my head hurt. But don't feel bad, because you're in great company. First
attempts are often like that – even for people who have been doing this
for a long time.
What, specifically, makes it hard to understand? Algorithmic complexity: nested loops
and conditionals, breaks, managing list indexes, and so forth. Whenever you perceive that type of complexity, it often helps to consider whether a more powerful data structure
would simplify the situation (I'm using "data structure" in a very broad sense).
In the rewrite offered below, we will use
a special iterable that allows us to peek at the next value without actually
consuming it every time. That one change drastically simplifies the bookkeeping
inside the main loop, and it also simplifies how we append the needed
remainder of missing values after we exit the loop.
# This is a third party library that is worth knowing about.
from more_itertools import peekable

# Your data, aligned so we can see what is going on.
# When you ask a question, it's a good idea to help your helpers.
xs = [
    'first = 1st', 'second = 2nd', 'third = 3rd', 'fourth = 4th',              'sixth = 6th',
    'first = A',   'second = B',   'third = C',                   'fifth = E', 'sixth = F',
                   'second = W',   'third = X',   'fourth = Y',   'fifth = Z', 'sixth = AA',
    'first = BB',
]

ys = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']

# Python has a builtin concept for missing data. Use it if you can.
# If you cannot, define a constant.
MISSING = None

# The results we want.
# When you ask a question, it's a good idea to provide this.
EXPECTED = [
    '1st',     '2nd',     '3rd',     '4th',     MISSING,   '6th',
    'A',       'B',       'C',       MISSING,   'E',       'F',
    MISSING,   'W',       'X',       'Y',       'Z',       'AA',
    'BB',      MISSING,   MISSING,   MISSING,   MISSING,   MISSING
]

# We will use a peekable iterable for both the Xs and the Ys.
xit = peekable(xs)
yit = None
results = []

# Process all Xs to build the results.
# A Y is consumed each time, and we get a fresh Ys iterable as needed.
# We consume an X only when current X and Y agree.
while xit:
    yit = yit or peekable(ys)
    x = xit.peek()
    y = next(yit)
    val = next(xit).split('= ')[-1] if y in x else MISSING
    results.append(val)

# The results should always contain a full cycle of Ys.
results.extend(MISSING for _ in yit)

# Check.
print(results == EXPECTED)


Job applicant email system I just wrote this and don't like how bulky it is, also given the fact I will have to add at least another if statement.

I was going to switch it to a case statement but wanted to check if there were even better ways to reduce the clutter.

string emailLetterPath = Server.MapPath("~/emails/rejected.htm");

if (jobApplicantAndJob.Jobs.Title == "Store Sales Manager" || jobApplicantAndJob.Jobs.Title == "Sales Representative")
{
     emailLetterPath = Server.MapPath("~/emails/TC1RejectedP3.htm");
}

if (jobApplicantAndJob.Jobs.Title == "Outside Sales Professional")
{
     emailLetterPath = Server.MapPath("~/emails/TC2RejectedP3.htm");
}

The default option should be the rejected.htm.

I was going to switch it to a case statement but wanted to check if there were even better ways to reduce the clutter.

You could load the mappings from job titles to emails into a (static) dictionary, and then do a dictionary look-up (using the default value if it's not in the dictionary).

The Dictionary<string,string> can be initialized with a collection initializer.

Using a (data-driven) dictionary instead of a (hard-coded) switch statement has the additional benefit that users can configure/maintain the behaviour by editing a configuration file (e.g. a tab-delimited 'CSV file' of title/email pairs) or database, instead of editing code.


Vectorize/speed-up exponentially weighted covariance calculation in R I have the following 2-column data.frame:

Data <- data.frame(matrix(rnorm(100),ncol = 2))

I would like to calculate the variance-covariance matrix as the exponentially weighted average of the past squared/cross observations (on an expanding window):

Where delta is set to be 60/61. Thus, at t=4, the sum runs from 1 to 4, and the averages are computed over the first 4 observations. I have managed to implement a function calculating the upper triangular part of the covariance matrix, but it is quite slow. Does anyone have ideas to improve the speed?

rollEWCov <- function(Data){
  res <- c()
  for(i in 1:nrow(Data)){ # Expanding window of data used to calc covariances
    means <-  colMeans(Data[1:i,])
    Cov <- matrix(0,nrow = ncol(Data),ncol=ncol(Data))
    for(k in 1:ncol(Data)){ # first data-column
      l <- k
      while(l <= ncol(Data)){ # second data-column
        Sum <- 0
        for(j in 1:i){ # calc sum of exponentially weighted average of past returns
          Sum <- Sum + (1-60/61)*(60/61)^(j-1)*(Data[i-(j-1),k] - means[k])*(Data[i-(j-1),l] - means[l])
        }
        Cov[k,l] <- Sum
        l <- l + 1
      }
    }
    res[[i]] <- Cov
  }
  return(res)
}

A key performance bottleneck in your code is your calculation of the Cov_t^{k,l} values:

Sum <- 0
for(j in 1:i){ # calc sum of exponentially weighted average of past returns
  Sum <- Sum + (1-60/61)*(60/61)^(j-1)*(Data[i-(j-1),k] - means[k])*(Data[i-(j-1),l] - means[l])
}
Cov[k,l] <- Sum

You are summing from j=1 through j=i by looping through the values individually and adding them up. In R you can get significant speedups by using the vectorized sum function:

Cov[k,l] <- sum((1-60/61)*(60/61)^(0:(i-1))*(Data[i:1,k] - means[k])*(Data[i:1,l] - means[l]))

Additionally, this part of the code hard-codes the choice of delta=60/61, which may make it harder to see what the code is doing or update to another delta value. It would be best to pass delta to the function and then use delta instead of 60/61 in this expression. Here is the updated function:

rollEWCovMod <- function(Data, delta){
  res <- c()
  for(i in 1:nrow(Data)){ # Expanding window of data used to calc covariances
    means <-  colMeans(Data[1:i,])
    Cov <- matrix(0,nrow = ncol(Data),ncol=ncol(Data))
    for(k in 1:ncol(Data)){ # first data-column
      l <- k
      while(l <= ncol(Data)){ # second data-column
        # calc sum of exponentially weighted average of past returns
        Cov[k,l] <- sum((1-delta)*delta^(0:(i-1))*(Data[i:1,k] - means[k])*(Data[i:1,l] - means[l]))
        l <- l + 1
      }
    }
    res[[i]] <- Cov
  }
  return(res)
}

To see the performance improvements of the vectorized sum, we can benchmark with a 500 x 2 matrix:

Data <- data.frame(matrix(rnorm(1000),ncol = 2))
system.time(rollEWCov(Data))
#    user  system elapsed
#  11.300   0.103  12.031
system.time(rollEWCovMod(Data, 60/61))
#    user  system elapsed
#   0.142   0.006   0.149
all.equal(rollEWCov(Data), rollEWCovMod(Data, 60/61))
# [1] TRUE

We obtained a 80x speedup and got identical results to the original function.


Get a random member of a container It was not obvious how to get a random member of a container. So I wrote a function to retrieve it given a generator.

namesapce ThorsAnvil
{
    namespace Util
    {
        using Distribution = std::uniform_int_distribution<int>;

        /* Get a distribution from [0, max)   */
        /* None maths nerds: Note the [ and ) */
        Distribution getDist(int max)
        {
            return Distribution{0, max - 1};
        }

        template<typename C, typename G>
        auto getRandomIteratorFromContainer(C& container, G& generator)
        {
            auto pos = container.begin();

            int     offset  = getDist(container.size())(generator);
            std::advance(pos, offset);

            return pos;
        }
    }
}

Long name

ThorsAnvil::Util::getRandomIteratorFromContainer is a really long name. I suggest something like getRandomElement or even randomElement.

Unnecessary function

getDist seems kind of unnecessary to me. I think it would be cleaner to construct the distribution directly.

std::uniform_int_distruction<int> dist{0, container.size() - 1};

Types

The integer type used for iterator arithmetic is typename C::difference_type. This is almost always equivalent to std::ptrdiff_t so to be crystal clear, use std::ptrdiff_t.

std::uniform_int_distruction<std::ptrdiff_t> dist{0, container.size() - 1};

Unnecessary variable

offset is initialized with a random offset and is only used once. If it's only used once then it doesn't really need to exist.

std::advance(pos, dist(generator));

Wrong function

std::advance modifies an existing iterator. This means that we need store the iterator, advance it, then return the iterator. That's three steps. std::next takes an iterator and returns an incremented one.

return std::next(container.begin(), dist(generator));

Covering all cases

Using .begin() and .size() is a little bit restrictive. If we use std::begin and std::size, this function will work on C-style arrays which is a nice. If we want to be even more general (as Toby mentioned in the comments), we can let ADL pick up the right function for containers that declare their own begin and size functions.

using std::begin;
using std::size;

Short names

My answer has been pretty nitpicky so far but this is particularly nitpicky. Long template parameter names that clearly describe the parameter are better than single character names.

template <typename Container, typename Generator>

How I would write it

After applying the above transformations. We get this function:

template <typename Container, typename Generator>
auto random_element(Container &con, Generator &gen) {
  using std::begin;
  using std::size;
  std::uniform_int_distribution<std::ptrdiff_t> dist{0, size(con) - 1};
  return std::next(begin(con), dist(gen));
}


Validating and averaging student grades I have myself a little challenge tonight. I've tried to come up with the shortest code for the problem below (the code is pretty self explanatory, except determinGrade there which follows the rule

  A - 90-100%
    B - 80-89%
    C - 70-79%
    D - 60-69%
    F - Below 60%

The code has to be PEP8 complient and no imports (std included) are allowed. Tell me if you can shorten the code further.

isValidScore = lambda n: 0 <= n <= 100
calcAverage = lambda *args: sum(args)/len(args)
determinGrade = lambda s: ['F', 'D', 'C', 'B', 'A'][max(0, (min(s, 99)/10)-5)]

def getValidScore():
    while True:
        try:
            s = int(raw_input('Input score: '))
            if isValidScore(s):
                return s
        except ValueError:
            pass
        print('Score has to be an integer in the range 0 to 100')

if __name__ == "__main__":
    scores = [getValidScore() for _ in range(5)]
    print('The scores are: ' + str(scores))
    print('The average is: ' + str(calcAverage(*scores)))
    print('The grade is: ' + determinGrade(calcAverage(*scores)))

Although this passes the pep8 tool as of version 1.5.5,
this is not PEP8 compliant:

  Function names should be lowercase, with words separated by underscores as necessary to improve readability.
  Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.

If you convert the lambda expressions to def statements, the result will be longer, but better.

Also, these statements are a bit tightly packed for my taste:

calcAverage = lambda *args: sum(args)/len(args)
determinGrade = lambda s: ['F', 'D', 'C', 'B', 'A'][max(0, (min(s, 99)/10)-5)]

Would have been better this way, but PEP8 does not require it:

calcAverage = lambda *args: sum(args) / len(args)
determinGrade = lambda s: ['F', 'D', 'C', 'B', 'A'][max(0, (min(s, 99) / 10) - 5)]

In this last statement, there are some redundant parentheses, this is equivalent:

determinGrade = lambda s: ['F', 'D', 'C', 'B', 'A'][max(0, min(s, 99) / 10 - 5)]

Instead of the min hack for the value of 100, how about this way:

determinGrade = lambda s: ['F', 'D', 'C', 'B', 'A', 'A'][max(0, s / 10 - 5)]

Last but not least, beware that in Python 3, 27 / 10 will give you 2.7 instead of 2 as in Python 2. As such, the determinGrade will try to use a float as the list index, and your script will break. Adopting Python 3 is probably only a matter of time, so it's good to be prepare for that, and use // to ensure that you will get an integer index:

determinGrade = lambda s: ['F', 'D', 'C', 'B', 'A', 'A'][max(0, s // 10 - 5)]

Suggested implementation

Putting the above suggestions together:

def is_valid_score(n):
    return 0 <= n <= 100

def calc_average(*args):
    return sum(args) / len(args)

def determine_grade(s):
    return ['F', 'D', 'C', 'B', 'A', 'A'][max(0, s // 10 - 5)]

def get_valid_score():
    while True:
        try:
            s = int(raw_input('Input score: '))
            if is_valid_score(s):
                return s
        except ValueError:
            pass
        print('Score has to be an integer in the range 0 to 100')

if __name__ == "__main__":
    scores = [get_valid_score() for _ in range(5)]
    print('The scores are: ' + str(scores))
    print('The average is: ' + str(calc_average(*scores)))
    print('The grade is: ' + determine_grade(calc_average(*scores)))


Simple Java MVC (swing) I'm a Java beginner currently practising MVC pattern and came up with this. Could you please check if this is a proper implementation of MVC and if there are any best practices that I have broken?

public class Appka {

    public static void main(String[] args) {

        Model model = new Model();
        Controller controller = new Controller(model);
        View view = new View(model, controller);
        model.addListener(view);

    }
}

public class Model {

    String value;
    List<StateChangedListener> listeners = new ArrayList<>();

    public Model() {

        this.value = "";
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
        notifyListeners();
    }

    public void addListener(StateChangedListener l) {
        listeners.add(l);
    }

    public void removeListener(StateChangedListener l) {
        listeners.remove(l);
    }

    public void notifyListeners() {
        listeners.forEach(l -> l.stateChanged());
    }
}

public class View extends JFrame implements StateChangedListener {

    private Model model;
    private Controller controller;
    private JLabel label1;
    private JLabel label2;
    private JButton button1;
    private JButton button2;

    public View(Model model, Controller controller) {
        this.model = model;
        this.controller = controller;
        initComponents();
    }

    private void initComponents() {

        button1 = new JButton();
        button2 = new JButton();
        label1 = new JLabel();
        label2 = new JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        button1.setText("1");
        button1.addActionListener(controller);

        button2.setText("2");
        button2.addActionListener(controller);

        label1.setText("label1");

        label2.setText("label2");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(button1)
                    .addComponent(label1))
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(label2)
                    .addComponent(button2))
                .addContainerGap(113, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(label1)
                    .addComponent(label2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(button1)
                    .addComponent(button2))
                .addContainerGap(30, Short.MAX_VALUE))
        );

        pack();
        setVisible(true);

    }

    @Override
    public void stateChanged() {
        label1.setText(model.getValue());
        label2.setText(model.getValue());
    }

}

public class Controller implements ActionListener {

    private Model model;

    public Controller(Model model) {
        this.model = model;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton clicked = (JButton) e.getSource();
        model.setValue(clicked.getText());
    }

}

interface StateChangedListener {

    public void stateChanged();

}

(this answer is advice and not a real code review, but I can't comment)

I discourage to use swing for your GUI. Java is replacing swing with JavaFX.
But that's not the only reason why I should use JavaFX. The most important reason is that with JavaFX it is easier to follow the MVC pattern.

A very good JavaFx and MVC tutorial I really recommend and wich shows the whole worflow and structure:
link


Printing 1,000,000 numbers in 1 sec. in Python Here's a fairly simple task from CSES Problem Set - Permutations 1070 that reads:

A permutation of integers 1,2, …, n is called beautiful if there are no adjacent elements whose difference is 1.
Given n, construct a beautiful permutation if such a permutation exist

The constraints are pretty tight:

Time limit: 1.00 s
Memory limit: 512 MB
1 ≤ n ≤ 10^6

Here's the code:
n = int(input())
if n == 2 or n == 3:
    print("NO SOLUTION")
elif n == 1:
    print(1)
elif n == 4:
    print("3 1 4 2")
else:
    for i in range(1, n + 1, 2):
        print(str(i) + " ", end=" ")
    for i in range(2, n + 1, 2):
        print(str(i) + " ", end=" ")

It passes all tests except for n = 1000000. For that test it takes 15 sec. on my machine. The code is in Python 3.8
The question is, what can can be improved in terms of printing the numbers?

Nice solution, few suggestions:

Printing the numbers one by one might be the issue. Generate the list of numbers first and then call print only once.
The case n==1 is already handled, so the first elif can be removed.

Applying the suggestions:
n = int(input())
if n == 2 or n == 3:
    print("NO SOLUTION")
elif n == 4:
    print("3 1 4 2")
else:
    beautiful_perm = [*range(1, n + 1, 2), *range(2, n + 1, 2)]
    print(' '.join(map(str, beautiful_perm)))

By inverting the ranges we don't need to check for n==4:
n = int(input())
if n == 2 or n == 3:
    print("NO SOLUTION")
else:
    beautiful_perm = [*range(2, n + 1, 2), *range(1, n + 1, 2)]
    print(' '.join(map(str, beautiful_perm)))

Runtime on CSES:
n = 906819 (CPython3)
Original: 0.92 s
Improved: 0.26 s

n = 1000000 (CPython3)
Original: timeout
Improved: 0.28 s

n = 1000000 (PyPy3)
Original: 0.61 s
Improved: 0.15 s


Singly linked list implementation in python 3 I have implemented a Singly linked list. It works well. But if you think something needs to be improved, say it. This code was tested in Python 3.7.4.

class Node(object):

    def __init__(self, data):
        self.data = data
        self.nextNode = None

class LinkedList(object):

    def __init__(self):
        self.head = None
        self.size = 0

    # O(1) !!!
    def insertStart(self, data):

        self.size = self.size + 1
        newNode = Node(data)

        if not self.head:
            self.head = newNode
        else:
            newNode.nextNode = self.head
            self.head = newNode

    def remove(self, data):

        if self.head is None:
            return

        self.size = self.size - 1

        currentNode = self.head
        previousNode = None

        while currentNode.data != data:
            previousNode = currentNode
            currentNode = currentNode.nextNode

        if previousNode is None:
            self.head = currentNode.nextNode
        else:
            previousNode.nextNode = currentNode.nextNode

    # O(1)
    def size1(self):
        return self.size

    # O(N)
    def insertEnd(self, data):

        self.size = self.size + 1
        newNode = Node(data)
        actualNode = self.head

        while actualNode.nextNode is not None:
            actualNode = actualNode.nextNode

        actualNode.nextNode = newNode

    def traverseList(self):

        actualNode = self.head

        while actualNode is not None:
            print(actualNode.data)
            actualNode = actualNode.nextNode

You are missing several important things for this code:

Type Annotations

Python 3.7 supports type annotations. Especially for a container class like this, you should fully use them.

Initializer parameters

Python containers generally all provide builder methods or class initializer functions that take other containers and use their contents. Consider:

dict(iterable,**kwarg)
list(iterable)
set(iterable)
str(object=b'', encoding='utf-8', errors='strict')
tuple(iterable)

If you're writing a Python container, you need to conform to expectations. I expect to be able to initialize the container when I create it.

Protocols & Magic methods

Python has a well-established set of protocols for implementing containers. You just have to decide what kind of container you're writing.

I would suggest that a singly-linked list is an Iterable, a Sequence, a MutableSequence and possibly a Set type.


Cycling through sibling elements on button click and assigning a class to the “active” element I am attempting to do something that seems pretty simple, but I'm not sure if it as performant as it could be. I'm looking to cycle through a set of elements and toggle a class to only show a single item at a time, looping back to the first item at the end.

$(document).ready(() => {
  const toggleButton = $('.btn-toggle');
  toggleButton.on('click', function toggleButtonClick() {
    const currentItem = $(this).parent('.itemtoggle')
      .find('li:not(.d-none)').toggleClass('d-none');
    let nextItem = currentItem.next();
    if (nextItem.length === 0) {
      nextItem = currentItem.parent('.items').find('li');
    }
    nextItem.first().toggleClass('d-none');
  })
  .parent('.itemtoggle')
  .find('li')
  .toggleClass('d-none')
  .first()
  .toggleClass('d-none');
});

Full code example on Codepen

Right now it is written using jQuery. Is there a better way to do this, in jQuery, Vanilla JS, or other?

You are doing a lot of DOM traversal. I'll show you the updated code and explain it.

HTML

Item 1

Item 2

Item 3

Item 4

  <button type="button" class="btn-toggle">Toggle Next</button>

CSS

.d-none {
  display: none;
}

JAVASCRIPT

$(document).ready(() => {
  const toggleButton = $('.btn-toggle');
  const items = document.querySelectorAll('.items > li');
  let index = 0;
  toggleButton.on('click', () => {
     $(items[index]).toggleClass('d-none');
     index = index + 1;
     if(index === items.length){
       index = 0;
     }
     $(items[index]).toggleClass('d-none');
  });
});

I updated the HTML so that the li's after the first have display none. In your previous code this was the initial state, so its better to set it in the HTML than using JavaScript to do it.

What i have done in JavaScript is that i store all
 and an associated index, then when you press Toggle Next, i just toggle the
 at the current index, and increment index by 1, if index === items.length, then it must mean we are out of bounds, because items[4] would be undefined, so we have to reset it to 0.

After increment, we toggle d-none on the new index.


Pandas add calculated row for every row in a dataframe I have a dataframe like so:
id  variable  value
1      x        5
1      y        5
2      x        7
2      y        7

Now for every row, I want to add a calculated row. This is what I am doing as of now:
a = 2
b = 5
c = 1
d = 3
df2 = pd.DataFrame(columns =  ["id", "variable", "value"])
for index, row in df.iterrows():
    if row['variable'] == 'x':
        df2 = df2.append({'id':row['id'], 'variable':'x1', 'value':a*row['value']+b}, ignore_index=True)
    else:
        df2 = df2.append({'id':row['id'], 'variable':'y1', 'value':c*row['value']+d}, ignore_index=True)
df = pd.concat([df, df2])
df = df.sort_values(['id', 'variable'])

And so finally I get:
id  variable  value
1      x        5
1      x1       15
1      y        5
1      y1       8
2      x        7
2      x1       19
2      y        7
2      y1       10

But surely there must be a better way to do this. Perhaps where I could avoid for loop and sorting, as there are a lot of rows.

iterrows
Of all the ways to iterate over a pandas DataFrame, iterrows is the worst. This creates a new series for each row. this series also has a single dtype, so it gets upcast to the least general type needed. This can lead to unexpected loss of information (large ints converted to floats), or loss in performance (object dtype).
Slightly better is itertuples
append
Appending row per row can be very slow (link1link2)
Better would be to assembly them in a list, and make a new DataFrame in 1 go.
vectorise
One easy change you can make is not iterating over the database in 'Python' space, but using boolean indexing
x = df["variable"] == "x"
y = df["variable"] == "y"

df2 = df.copy()
df2.loc[x, "value"] = df.loc[x, "value"] * a + b
df2.loc[y, "value"] = df.loc[y, "value"] * c + d
df2.loc[x, "variable"] = "x1"
df2.loc[y, "variable"] = "y1"

wide vs long
This can be made a lot easier by reforming your dataframe by making it a bit wider:
df_reformed = (
    df.set_index(["id", "variable"]).unstack("variable").droplevel(0, axis=1)
)

variable  x   y
id
1     5   5
2     7   7

Then you can calculate x1 and y1 vectorised:
df_reformed.assign(
    x1=df_reformed["x"] * a + b,
    y1=df_reformed["y"] * c + d
)

and then convert this back to the long format:
result = (
    df_reformed.assign(
        x1=df_reformed["x"] * a + b,
        y1=df_reformed["y"] * c + d
    )
    .stack()
    .rename("value")
    .sort_index()
    .reset_index()
)


Send messages in TCP-based communication system I am working on a TCP-based Communication System.

I wrote a working function for sending Textmessages and remotely opening a MessageBox. I would like to know how elegant this piece of code is and how I may improve it, cause it seems messy to me.

Client:

private void btnSend_Click(object sender, EventArgs e)
{
    NetworkStream stream = client.GetStream();

    BinaryWriter w = new BinaryWriter(stream);

        byte[] msg = new byte[4096];
        msg = Encoding.ASCII.GetBytes("%" + txtMsg.Text + "&");

        w.Write(msg, 0, msg.Length);

}

private void btnMsgBox_Click(object sender, EventArgs e)
{
    NetworkStream stream = client.GetStream();

    byte[] msg = new byte[4096];

    msg = Encoding.ASCII.GetBytes("%DisplayRemoteMessageBox&" + txtMsg.Text + "#");
    stream.Write(msg, 0, msg.Length);
}

Server:

while(true)
{
    while(client.Connected)
    {
        byte[] msg = new byte[4096];
        var count = stream.Read(msg, 0, msg.Length);

        string returnData = Encoding.ASCII.GetString(msg, 0, count);

        string command = returnData.Substring((returnData.IndexOf("%") + 1), (returnData.IndexOf("&") -1));

        switch(command)
        {
        case "DisplayRemoteMessageBox":
                returnData = returnData.Replace("%DisplayRemoteMessageBox", "");
                int startInd = returnData.IndexOf("&");
                int len = returnData.IndexOf("#");

                returnData = returnData.Substring((startInd + 1), (len - 1));
                MessageBox((IntPtr)0, returnData, "TestBox", 0);
                 break;
        case "":
                client.Client.Disconnect(true);
                Console.WriteLine("User disconnected");
                 break;
        default:
                returnData = returnData.Substring(1, (returnData.Length - 2));
                Console.WriteLine(returnData);
                 break;
        }
    }
}

Networking Concerns

I'm going to assume that stream is a NetworkStream in the Server. It is really really important that you understand that stuff which 'just happens to work' with a 'normal' stream, won't work with a NetworkStream, which also doesn't provide a 'complete' Stream implementation (being non-seeking and such it can't).
Your code currently could behave very oddly and somewhat non-deterministically depending on the interface between the server and client computers, and likely the lengths of messages.
I'm going to provide a full-enough answer here, because I can't find any that I really like on SO (I'm sure there are good ones, I just can't find them). Networked code is hard enough to write that I won't say anything about buffering and the performance implications thereof (not least because I don't really understand it myself, and have never bothered to properly profile any of my code).
Note that there are loads of examples of this deficiency all over the web (and not enough explanations of the problem, I hope mine isn't too painful).

Unfortunately, network programming isn't quite so easy: because TCP is stream based, you never really know when a 'message' has ended. The problem with your code is a result of the lone call to stream.Read(byte[], int, int)... and unfortunately the MSDN example has the same problem!
Essentially, this code is insufficient:
byte[] msg = new byte[4096];
var count = stream.Read(msg, 0, msg.Length);
string returnData = Encoding.ASCII.GetString(msg, 0, count);
string command = returnData.Substring((returnData.IndexOf("%") + 1), (returnData.IndexOf("&") -1));

I imagine you will never see this problem if you test the code on a single machine; however, over the internet I suspect it will become somewhat apparent with longer messages. As I said, Read can't know when the message your client has sent ends... so when should it return? The answer is... I don't know, it just does at some point: I don't know if there are any guarantees, and it's most certainly OS/Configuration dependant, so you shouldn't make any assumptions.
Currently you are just hoping that when calling "Read" you will receive a full message: you could well receive only part of a message, or even two messages (or parts of two messages, etc.). TCP ensures that you will receive the stream of bytes in the right order, or know that you have lost communications, but it has no concept of 'packets' (or messages) like UDP does, which is why TcpClient exposes a NetworkStream.
Example:
Client Sends "%DisplayRemoteMessageBox&Hello, World!#"
Server Received "%DisplayRemoteMessageB" -> print to console
Server Received "ox&Hello, World!#" -> print to console

The server can cut-up the stream any way it likes, so you have to design a protocol so that you can work out where stuff starts and ends (if necessary, which it is for you).
How exactly you want to 'fix' this depends on your system. You are using ASCII explicitly, so you could easily enough do a byte-by-byte (char-by-char) 'text' stream analysis to extract messages (e.g. look for % to start a message, and wait for # to end it). This is how some older protocols like IRC work, where they use some method to identify new-lines in communications, which defines the separation between messages. This involves looking at each byte you read, deciding if it has a special meaning, and acting on it accordingly. This can be fiddly and is easy to make inefficient.
A cleaner solution is to define a simple protocol which allows you to determine the length of a 'message' before you read it. The main advantage of this is that you no longer need to know what a message 'looks like' to read it: this means it can look like )anything_ (note that your current code doesn't allow you to send a # as part of a message, because # has meaning). This will (probably) be a binary protocol, where you define each message as a 'packet', which starts by declaring its length, and then streams the message.
On the client, you simply have to work out how long your messages are, and send the length before you send the message. On the server, you start by reading the length, and then you read that many bytes so you know that you have the full message. You could process the message as you receive it (e.g. for file transfer, you wouldn't wait until you've received all the bytes to start writing it disk), but for small messages you can just accumulate all the bytes in a buffer and process it in one.
I always use this binary 'packet' method for networking - not least because I have no desire to think about Unicode and its implications - so here is a rough sketch of how you might implement it to send individual strings (with lots of comments for in-line explanation). I'll make no guarantees that this code will work out-of-the-box.
Notice about BinaryWriter and friends
Much of what I have just described (and below implement) is facilitated by the BinaryReader and BinaryWriter classes in the BCL. However, both these classes assume/enforce little-endian byte order, which is not ideal when most of the networking world has agreed on big-endian. I present the below because I forgot that BinaryWriter was little-endian to show the concepts above explicitly, and to show a viable solution for big-endian communications (e.g. when interoping with existing big-endian protocols / variable endian protocols (I'm sure they exist))
Client Side
As suggested by BKSpurgeon, factor out the message writing in your two event handlers: the code is basically the same at the moment. What you want is a new method to send a string to the server, a very simple API indeed (which is no bad thing).
/// <summary> Sends a length-prepended (Pascal) string over the network </summary>
private void SendMessage(string message)
{
    NetworkStream networkStream = client.GetStream();

    // turn the string message into a byte[] (encode)
    byte[] messageBytes = Encoding.ASCII.GetBytes(message); // a UTF-8 encoder would be 'better', as this is the standard for network communications

    // determine length of message
    int length = messageBytes.Length;

    // convert the length into bytes using BitConverter (encode)
    byte[] lengthBytes = System.BitConverter.GetBytes(length);

    // flip the bytes if we are a little-endian system: reverse the bytes in lengthBytes to do so
    if (System.BitConverter.IsLittleEndian)
    {
        Array.Reverse(lengthBytes);
    }

    // send length
    networkStream.Write(lengthBytes, 0, lengthBytes.Length);

    // send message
    networkStream.Write(messageBytes, 0, length);
}

// example calls
private void btnSend_Click(object sender, EventArgs e)
{
    msg = "%" + txtMsg.Text + "&";
    SendMessage(msg);
}

// example calls
private void btnMsgBox_Click(object sender, EventArgs e)
{
    msg = "%DisplayRemoteMessageBox&" + txtMsg.Text + "#";
    SendMessage(msg);
}

Hopefully this is mostly pretty easy to follow. Note the 'endian flip' of the length: Endianness is a nightmare on its own, and the .NET libraries do not help much. Note the remarks for BitConverter.GetBytes(int): to be efficient, this will just be a blit, which means the result depends on the hardware you are using. This is fine if the destination has the same endianness, but with networking you can't assume that, so we agree to send big-endian, which means flipping the bytes if we are on a little-endian machine. We don't use a BinaryWriter because it is little-endian only, so it's harder to change the endianness (useful for demonstration and compatibility). This is only necessary for primitives like integers; ASCII (and UTF) are both defined the same way for a big- or little-endian system, so there is no issue with the string.
When you start writing more and more code like this, you'll end up writing dedicated methods for sending integers, strings (the protocol above is basically just sending a length-prefix 'Pascal' string), and other primitives; similarly for the server.
Server Side
on the client, we provide a method to 'send' a string. Duly, on the server, we should probably provide a message to 'receive' a string. I will sketch a very simple blocking solution. For real code, you probably won't something asynchronous, and that facilitates buffer reuse.
Reading a string requires reading the length, and then the string itself. This is two separate reads, so let's write one method to do this:
Essentially, because we can't trust NetworkStream.Read(,,) to give us the right number of bytes, we have to repeatedly call NetworkStream.Read(,,) and accumulate the bytes it gives us into a buffer. We only return the buffer to the caller when it is full (i.e. we have read exactly the requested number of bytes).
/// <summary> Reads a number of bytes from the stream </summary>
private byte[] ReadBytes(int count)
{
    NetworkStream networkStream = client.GetStream();

    byte[] bytes = new byte[count]; // buffer to fill (and later return)
    int readCount = 0; // bytes is empty at the start

    // while the buffer is not full
    while (readCount < count)
    {
        // ask for no-more than the number of bytes left to fill our byte[]
        int left = count - ReadCount; // we will ask for `left` bytes
        int r = networkStream.Read(bytes, readCount, left); // but we are given `r` bytes (`r` <= `left`)

        if (r == 0)
        { // I lied, in the default configuration, a read of 0 can be taken to indicate a lost connection
            throw new Exception("Lost Connection during read");
        }

        readCount += r; // advance by however many bytes we read
    }

    return bytes;
}

There are few ways that the code above can go wrong depending on the configuration (timeout, lost client, etc.), most of which involving a complete breakdown in communication, so the exception thrown will be a welcome one, and can be handled as appropriate. It is 'blocking', which means that it will not return until it has read count many bytes. Asynchronous versions can be written using async or simple call-backs (again, I can't find a good SO reference for this at the moment, but I'm sure I've seen one in the past). With the while loop, it looks like this code will cook your computer, but in reality NetworkStream plays 'nicely' with the TCP stack, and will block until at least the first byte is read.
Using this ReadBytes(int) method, we can write the ReadMessage method we really want:
/// <summary> Reads the next message from the stream </summary>
private string ReadMessage()
{
    // read length bytes, and flip if necessary
    byte[] lengthBytes = ReadBytes(sizeof(int)); // int is 4 bytes
    if (System.BitConverter.IsLittleEndian)
    {
        Array.Reverse(lengthBytes);
    }

    // decode length
    int length = System.BitConverter.ToInt32(lengthBytes, 0);

    // read message bytes
    byte[] messageBytes = ReadBytes(length);

    // decode the message
    string message = System.Text.Encoding.ASCII.GetString(messageBytes);

    return message;
}

Note that there is an obvious read -> decode -> consume process going on here. For anything but the most simple system, I would write a separate ReadInt method which the ReadMessage method would call.
With ReadMessage written, you can refit the server code, which becomes much tidier:
while(client.Connected)
{
    string message = ReadMessage();

    string command = message.Substring((message.IndexOf("%") + 1), (message.IndexOf("&") -1));

    switch(command)
    {
        // ...
    }
}

Note that not much has changed in the server or client: they are still using the same protocol you have set up for sending a command: all that has been added is a robust mechanism for sending and receiving a single string. Breaking the code up so that each unit of work is its own method makes it much more maintainable.
As this is really meant to be a code review, I should point out that the second argument for message.Substring(,): it is meant to be a length, so you need to subtract the start position for this to work as intended). I have also taken the liberty of renaming returnData as suggested in BKSpurgeon's answer.
I put the above into a petty test program to content myself that it compiles and isn't completely broken: example gist; it starts a simple server which just prints messages to the screen, and demonstrates simple lost connection handling (which can be jolly annoying)
More comments on BinaryWriter and friends in the context of the question
Essentially, the above SendMessage and ReadMessage methods perform a big-endian 32bit-length-prefix string transmission. If you can accept little-endian encoding, and the particulr prefix regime that they use, then you can get away with just wrapping your NetworkStream  with a BinaryReader/BinaryWriter and using ReadString() and Write(String). Note that these classes use UTF-8 by default, but this is configurable in the constructors. These methods use a variable prefix length for efficiency purposes: you can see an implementation on source.dot.net. Note also that length-prefixing is invaluable when sending any discrete packet, and using these built-ins will only help if you are exclusively sending strings. If you do only need strings (e.g. if you are serialising everything as text/XML/JSON before transmitting it), and you can get way with the other constraints (e.g. if you control the protocol so can choose the endianness and prefix regime), then the following may suffice for you:
public void SendMessage(string message)
{
    NetworkStream networkStream = TcpClient.GetStream();
    using (var binaryWriter = new System.IO.BinaryWriter(networkStream, System.Text.Encoding.UTF8, leaveOpen: true))
    {
        binaryWriter.Write(message);
    }
}

public string ReadMessage()
{
    NetworkStream networkStream = TcpClient.GetStream();
    using (var binaryReader = new System.IO.BinaryReader(networkStream, System.Text.Encoding.UTF8, leaveOpen: true))
    {
        return binaryReader.ReadString();
    }
}

The parameter leaveOpen is important here, because the code creates a new BinaryReader/Writer each call, and otherwise it would close the stream when it is disposed. Ideally you would create and hold onto a single instance of each, and dispose them along with the TCPClient.
Other
This SO answer about detecting a lost TCP connection while reading may be of general interest: note that it uses a combination of BinaryRead and a ReadBytes style loop to read a length-prefixed packet for a specific purpose.


Leetcode 3 sum code optimisation I was working on 3sum problem on leetcode
Question
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4]
A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

My Solution
var threeSum = function(nums) {
    let out = []
    let seen = {}
    for(let i = 0; i < nums.length; i++){
        remainingArr = nums.filter((d,id) => id != i);
        //Calling twoSum on remaining array
        twoSum(remainingArr, -nums[i], out, seen)
    }
    //Return in expected format by splitting strings and forming arrays
    return out.map(d => d.split(',')).filter(d => d.length > 0)
};

var twoSum = function(nums, target, out, seen){
    let myMap = {}
    for(let i = 0; i < nums.length; i++){
        if(myMap[target - nums[i]] != undefined){
            //If match found convert it to string so that we can test for dupicates
            let val = [target - nums[i], nums[i], -target].sort((a,b) => a - b).join(',');
            //Test for duplicates
            if(!seen[val]) {
                out.push(val)
                seen[val] = true
            }
        }
        myMap[nums[i]] = i;
    }
}

The above solution fails for last 2 very large test cases.
For the 2sum implementation I have used the hash map solution rather than 2 pointers.
According to solutions on leetcode I can see the best possible time complexity here is \$O(N^2)\$. But isn't my solution also \$O(N^2)\$ (as i'm using seen map inside the inner loop).
How can I optimize this further?

Performance
This is a performance only review and does not address any styling or composition.
Code examples are focused on performance with no attention given to readability, naming, or re-usability
Time complexity != performance
Time complexity is not a measure of performance. It is a measure of how performance changes as the input size changes.
Two functions can have the same time complexity but very different performance metrics.

Improving performance
Looking at your code I see some code that will negatively effect performance.
Your original code cleaned up a little. Semicolons, spaces and the like.
threeSum

function threeSum(nums) {
let out = [];
let seen = {};
for (let i = 0; i < nums.length; i++) {
    remainingArr = nums.filter((d, id) =>  id != i);
    twoSum(remainingArr, -nums[i], out, seen);
}
return out.map(d => d.split(',')).filter(d => d.length > 0);
};

function twoSum(nums, target, out, seen) {
let myMap = {};
for (let i = 0; i < nums.length; i++) {
    if (myMap[target - nums[i]] != undefined) {
        let val = [target - nums[i], nums[i], -target].sort((a,b) => a - b).join(',');
        if (!seen[val]) {
            out.push(val)
            seen[val] = true
        }
    }
    myMap[nums[i]] = i;
}
}

Major performance hits
The biggest problem is the line ...
        if (myMap[target - nums[i]] != undefined) {

where the most likely outcome is that myMap[target - nums[i]] is undefined.
Set or Map rather than Object
When JS sees a property name it needs to locate that property.
First it looks at the objects own properties. If that property does not exist, it then starts a recursive search up the prototype chain.
If the result is undefined it will have to have searched all the way up the prototype chain before it can return undefined. As this is the  most likely outcome this line adds a lot of additional (under the hood) overhead.
You can use a Set to avoid the need to traverse the prototype chain.
Memory management
There is also an incurred memory overhead because you create and release the object myMap each time the function twoSum is called.
Because javascript does not free up memory until  either

forced to due to low memory,
or when the code is at idle (Presumably in the leetcode environment that is after the function threeSum has exited and before the result is verified)

All the created myMap slowly eat up memory and will incur a GC (garbage collection) overhead. On a shared environment such as leetcodes cloud processing network memory allocated to a task can be rather small meaning forced GC calls are much more likely.
To avoid memory management overheads reduce the amount of work by reducing the number of new objects created.
In example threeSum1 I moved myMap to the first function and pass it to the second. I clear the map in the second function which is less of a management hit than creating and destroying a new one.
threeSum1

function threeSum1(nums]) {
const out = [];
const seen = new Set();
const myMap = new Set();
for (let i = 0; i < nums.length; i++) {
    remainingArr = nums.filter((d,id) =>  id != i);
    twoSum1(remainingArr, -nums[i], out, seen, myMap);
}
return out.map(d => d.split(',')).filter(d => d.length > 0);
};

function twoSum1(nums, target, out, seen, myMap) {
const b = -target;
myMap.clear();
for (let i = 0; i < nums.length; i++) {
    const a = nums[i], idx = target - a;
    if (myMap.has(idx)) {
        let val = [idx, a, b].sort((a,b) => a - b).join(',');
        if (!seen.has(val)) {
            out.push(val);
            seen.add(val);
        }
    }
    myMap.add(a);
}
}

More info

MDN Allocations

MDN Garbage collection

Minor improvements
You use Array.sort to sort the 3 values and then Array.join  them to get a unique key for the 3 values that sum to 0.
let val = [target - nums[i], nums[i], -target].sort((a,b) => a - b).join(',');

JavaScript's sort knows nothing about the array or why you are sorting it
For 3 items there are only 6 resulting outcomes, requiring at most 4 compares. You don't want the sorted array you just want to know how to build the key.
Building a small string using join is slower than building it manually using concatenation operators.
Thus we can remove the sort and use a set of if, else. and ternaries ? to build the key. No need to swap items in an unneeded array (an array that will use memory management just to exist). No need to use the slow join function to create the key.
Additional improvements.
For the best performance avoid

Indexing into arrays
Repeating calculations
Iterating over arrays more often than needed.
Manipulating Strings

Final code
Assuming that the order of items in each array in the returned array does not matter, and that the items can be Numbers (not Strings) we can remove the need to map and filler the result.
We store items in vars rather than indexing into the array nums[i] each time we want the value. eg a = nums[i]
We calculate values only once. eg b = -target, idx = target - a
threeSum2

function threeSum2(nums) {
var i = 0;
const out = [], seen = new Set(), map = new Set();
while (i < nums.length) {
    twoSum2(nums.filter((d,id) =>  id != i), -nums[i++], out, seen, map);
}
return out;
};
function twoSum2(nums, target, out, seen, map) {
var val = "", i;
const b = -target;
map.clear();
for (i = 0; i < nums.length; i++) {
    const a = nums[i], idx = target - a;
    if (myMap.has(idx)) {
        if (a < b && a < idx) { val =  idx < b ? "" + a + idx + b : "" + a + b + idx }
        else if (b < idx) { val =  idx < a ? "" + b + idx + a : "" + b + a + idx }
        else {  val =  a < b ? "" + idx + a + b : "" + idx + b + a }
        if (!seen.has(val)) {
            out.push([a, b, idx]);
            seen.add(val);
        }
    }
    map.add(a);
}
}

Results
Below are the test results for the 3 functions above.

threeSum Your original functions with changes unrelated to performance.
threeSum1 Major performance changes
threeSum2 Minor performance changes

The first test is on a set of 100 arrays 100 items long with an evenly distributed random set of integers in the range -10000 to 10000

Note threeSum2 is 5 time faster than original.
Note threeSum1 is only marginally quicker as the optimizations target only the resulting output data.

Name
Mean time 1
Call per sec
Rel performance
Total time
Calls

threeSum2
1,455.175µs
687
100.00%
1,412ms
970

threeSum1
1,547.062µs
646
94.03%
1,624ms
1,050

threeSum
7,047.454µs
141
20.52%
6,907ms
980

I don`t know the nature of the arrays that leetcode send the function.
The following table shows the result if we focus on the code that creates the result. This is done by reducing the range of values of the input to increase the resulting out array length.
Testing is on a set of 100 arrays 100 items long with an evenly distributed random set of integers in the range -100 to 100

Name
Mean time 1
Call per sec
Rel performance
Total time
Calls

threeSum2
1,904.629µs
525
100.00%
2,000ms
1,050

threeSum1
3,219.081µs
310
59.05%
3,380ms
1,050

threeSum
6,522.878µs
153
29.14%
5,871ms
900

The results show that threeSum2 is the quickest, either by a small or large margin depending on the number of matches found in the input.
Will it pass the leetcode test?
Will it be fast enough to pass the tests? That I do not know as I have not tried this example.
I do know that leetcode test times can swing wildly (from best to worst for the very same code) . Although I do not know as a fact, why, I strongly suspect that run time performance is effected by number of users using the service.
It is my experience (as an .au user) that to get the best results is to use the service in off peek times.

More
As i wrote this answer I forget to look into the array you filter
remainingArr = nums.filter((d,id) =>  id != i);

There is opportunity for more optimization in this line worth about ~5% performance increase.
Hints

use a Set and remove items using Set.delete tracking removed items, then replace them for the next pass with Set.add You can
iterate a set using for (const v of remainingArr) {

Or All the filter does is remove one element at the current index from the array. If you passed that index to the second function rather than a filtered array.

Test settings
Test settings. Same for both tests

Env: Chrome 89.0.4389.90 (64-bit). Laptop Passive cooling (ambient 17.9°)
Test Cycles.......: 100
Groups per cycle..: 1
Calls per group...: 10
Cool down 2........: 1,000,000µs

1 In microseconds µs (One millionth second)
2 time between cycles


Search a list recursively and return the index of the smallest value I was asked to define a function that takes a list as an argument and returns the index of the smallest value.

This is what I came up with:

def index_finder(lst):
    """
    parameters: lst of type list
    returns: index of the lst's smallest value
    """
    for i in range(len(lst)):
        if lst[i]==index(lst):
            print(i)
    return None

def index(lst):
    """
    parameters: lst of type list
    returns: the smallest value of that lst
    """
    if len(lst)==1:
        return lst[0]
    if lst[0]<lst[1]:
        lst.append(lst[0])
    return index(lst[1:])

index_finder([3,2,4,0,1,5,-6,2,5])

This will output the following:

6

As you can see I had to use separate functions in order to get the result. Is there a concise, yet simple way to do this?

By concise I mean short and by simple I mean using only simple functions.

Yes, there is a concise way to do this, even without a recursive function and that is to use the built-in min function with a custom key:

from operator import itemgetter

def min_index(x):
    return min(enumerate(x), key=itemgetter(1))[0]

The enumerate function adds the indices and the operator.itemgetter ensures that min cares only about the actual value (here it is equivalent to lambda t: t[1]). The [0] at the end gets the index from the minimum tuple.

The usage is almost the same as your function, it returns the value so you have to  print it yourself. This is actually good practice because this way you can use the output of the function for other things afterwards.

if __name__ == "__main__":
    print(min_index([3,2,4,0,1,5,-6,2,5]))
    # 6

If you want to use numpy (i.e you are going to do some heavy calculations with these objects), there is a function which does exactly what you want already implemented, numpy.argmin:

import numpy as np

np.argmin([3,2,4,0,1,5,-6,2,5])
# 6


First non repeated character Problem Statement :
Print the first non repeating character in a string.
Example :
In the string somecharsjustdon'tliketorepeat, m is the first non-repeating charecter.

My attempt :
New Code : Old one was not working as expected so I have updated the post. Old code can be found below new code
public class FirstNonRepeatedChar{
    static boolean isRepeated(String str, char c){
        int count = 0;
        for(char ch: str.toCharArray()){
            if(c == ch){
                count++;
            }
        }

        return count > 1;
    }

    static void printFirstNonRepeatedChar(String str){
        boolean found = false;

        for(char c : str.toCharArray()){

            if(! isRepeated(str, c)){
                found = true;
                System.out.println(str + " : " +c);
                break;
            }
        }

        if(!found){
            System.out.println(str + " : No non-repeated char");
        }
    }

    public static void main(String [] args){
        String []testCases = {"aaabbcc", "sss", "121", "test", "aabc"};

        for(String str: testCases){
            printFirstNonRepeatedChar(str);
        }
    }
}

Old code
public class FirstNonRepeatedChar{

    public static void main(String [] args){
        String str = "somecharsjustdon'tliketorepeat";

        loopI:
        for(int i = 0;i<str.length();i++){
            for(int j = i+1; j<str.length();j++){
                if(str.charAt(i)==str.charAt(j))
                    continue loopI;
            }
            System.out.println(str.charAt(i));
            break;
        }
    }
}

I want to ask :

Is there better way to solve this problem? Especially, is there efficient way to do this using built-in classes?
Can I reduce complexity?
Is there any case where my code may fail to generate appropriate result? and how can I avoid these failures?

Thanks in advance!

Welcome to Code Review. There are already excellent answers, I am adding an alternative solution running in \$O(n)\$ and relatively simple to understand.
private static void printFirstNonRepeatedChar(String str) {
    // LinkedHashMap maintains the insertion order
    Map<Character, Integer> freq = new LinkedHashMap<>();

    // Create map of frequencies
    for (Character c : str.toCharArray()) {
        if (freq.containsKey(c)) {
            freq.put(c, freq.get(c) + 1);
        } else {
            freq.put(c, 1);
        }
    }

    // Find first character with frequency 1
    for (Entry<Character, Integer> entry : freq.entrySet()) {
        if (entry.getValue() == 1) {
            System.out.println(entry.getKey());
            break;
        }
    }
}

The map freq contains the frequencies of the characters. For example, given the string aabbc, the map will be:

a -> 2
b -> 2
c -> 1

LinkedHashMap maintains the insertion order so after building the map it's enough to find the first entry with frequency 1.
This is the same but using Streams:
private static Character findFirstNonRepeatedChar(String str) {
    Map<Character, Long> freq = str.codePoints()
            .mapToObj(c -> (char) c)
            .collect(Collectors.groupingBy(Function.identity(),
                                           LinkedHashMap::new,
                                           Collectors.counting()));
    return freq.entrySet().stream()
            .filter(e -> e.getValue()==1)
            .map(Map.Entry::getKey)
            .findFirst().orElse(null);
}

Time complexity
Your solution runs in \$O(n^2)\$, where \$n\$ is the length of the input string. I highlighted in your code the relevant parts:
static void printFirstNonRepeatedChar(String str){
    // O(n)
    for(char c : str.toCharArray()){
        // isRepeated runs in O(n)
        if(! isRepeated(str, c)){
           // O(1)
        }
    }
    //..
}

As @Joop Eggen said, for small input strings you need to benchmark the solutions to really see the difference, but for large inputs the Big O notation must be considered.
Testing and reusability
Generally, it's better to return a result instead of printing in the method. It's easier to test and reuse. In your case the method could return the character or null. For example:
static Character printFirstNonRepeatedChar(String str){
    //...
        if(! isRepeated(str, c)){
            return c;
        }
        return null;
}

Now the method is easy to test:
@Test
public void findFirstNonRepeatedCharTest() {
    assertEquals(Character.valueOf('c'),findFirstNonRepeatedChar("aabbc"));
    assertNull(findFirstNonRepeatedChar("aa"));
}

Minor changes

In the method printFirstNonRepeatedChar you can just return; instead of using the flag found and break.


Validating a JOptionPane ConfirmDialog I use this code to make sure that the user didn't leave the combo box empty before pressing OK

            int option=-1;
            while(cboFruits.getSelectedItem() == null){
             option = JOptionPane.showConfirmDialog(null, message, "Fruits", JOptionPane.OK_CANCEL_OPTION);
             if (!(option == JOptionPane.OK_OPTION))
                 break;
             if(cboFruits.getSelectedItem() == null)
                 JOptionPane.showMessageDialog(null, "Select a fruit");
            }

Is there a better alternative to this that doesn't involve creating my own Dialog? The combo box gets filled with data when another combobox changes its value, so putting a value by default is not an option.

Your approach seems fine. But some minor improvements are possible:

It's unnatural to write !(x == y), the more natural way is x != y
I'm wondering if option is needed outside the loop are all. If not, then you should declare and initialize it inside the loop.
in every iteration, you check cboFruits.getSelectedItem()== null twice: once after the use clicked OK, and then again in the loop condition. It would be better to rearrange this code in a way that the condition is checked once per iteration.
It's recommended to use braces always, even with single line if statements