texts:
I created a simple log-in system in Java for a project. Security isn't a concern here, hence the plaintext password, but I'm interested in how I can improve the quality of my code. Everything seems to work but it just feels like messy code.

public boolean logIn(String name, String password)
{
    if (getLoggedInUser() != null)
    {
        throw new IllegalArgumentException("You are already logged in");
    }

    boolean login = false;

    for (User user: getUsers())
    {
        if (user.toString().equals(name) && user.getPassword().equals(password))
        {
            loggedInUser = user;
            login = true;
        }
    }
    if (!login) //what if the username + password combo is not correct
    {
        for (User user: getUsers())
        {
            if (user.toString().equals(name))
            {
                throw new IllegalArgumentException("Your password is incorrect");
            }
        }
        throw new IllegalArgumentException("Your username is incorrect");
    }
    return login;
}


texts: Given 2 numbers a and b find the smallest number greater than b by interchanging the digits of a and if not possible print -1

texts:
I have made the solution for this question it is based on backtracking. Can anyone suggest me how to make it work faster, I haven't practiced backtracking that much, although my solution seems to work. Please check it out

    class Test {
    static int ans = Integer.MAX_VALUE;

    static void f(char[] a, String s, int r, boolean[] vis, int b) {
        // System.out.println(s);
        if (r == 0) {
            int x = Integer.parseInt(s);
            if (x > b && x < ans)
                ans = Math.min(x, ans);

            return;
        }

        for (int i = 0; i < a.length; i++) {
            if (!vis[i]) {
                s += a[i];
                vis[i] = true;
                f(a, s, r - 1, vis, b);
                s = s.substring(0, s.length() - 1);
                vis[i] = false;
            }
        }

    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        char[] a = sc.next().toCharArray();
        // System.out.println(Arrays.toString(a));
        boolean[] vis = new boolean[a.length];
        int b = sc.nextInt();
        f(a, "", a.length, vis, b);

        System.out.println(ans == Integer.MAX_VALUE ? -1 : ans);

    }
}

vis array is used to track which element is already picked same thing
which we do in DFS.
r is the count of remaining elements in a.


texts: Will multi-threading or other method make my program run faster?

texts:
I didn't use multi-threading so far as I didn't need to. But as far as I've read, implementing them will make my program slightly faster than it actually is.

from validate_email import validate_email
import os

# the program is reading each line from "emails.txt" and after it checks each email it will remove duplicates and sort the godd / bad emails

def verify_emails(all_emails_file, all_good_emails_file, all_bad_emails_file):
    with open(all_emails_file) as f: all_emails = f.readlines()

    rs_emails = [elem.strip('\n') for elem in all_emails]
    rs_emails_set = set(rs_emails)  # remove duplicates

    good_emails_file, bad_emails_file = open(all_good_emails_file, 'w+'), open(all_bad_emails_file, 'w+')

    for email in rs_emails_set:
        if validate_email(email, verify=True):
            print >> good_emails_file, email
        else:
            print >> bad_emails_file, email

if __name__ == "__main__":
    clear = lambda: os.system('cls')
    clear()
    try:
        verify_emails("emails.txt", "good_emails.txt", "bad_emails.txt")
    except:
        print "\n\nFile with emails could not be found. Please create emails.txt and run the program again\n\n"

My code is perfectly functional, but when it handles big files ( > 2k rows ) it runs really slow. I'd like to take the best out of it and make it as faster as possible using multi-threading or any other methods.

I'd like when answering, if possible, somebody to explain me whether using multi-threading will help me optimize the program or not. More, I'd like somebody to also explain from his / her experience how can I optimize my code


texts: Table printing code using a fluent interface

texts:
Let's say you want to display something like:

One Two Three Four
1   2   3     4

And since you hate the idea of predefining the widths of the columns you want to print it with something like this:

public static void main(String[] args) {
    new Columns()
       .addLine("One", "Two", "Three", "Four")
       .addLine("1", "2", "3", "4")
       .print()
       ;
}

Either listing below can do this.  Which is easier to read?  How would you improve either of them?  Do either paint us into a corner?  Any multithreaded concerns? How could it be made extensible?  Would the getThis() trick help here or is it a bad idea?

Listing A

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

public class Columns {

    List<List<String>> lines = new ArrayList<>();
    List<Integer> maxLengths = new ArrayList<>();
    int numColumns = -1;

    public Columns addLine(String... line) {

        if (numColumns == -1){
            numColumns = line.length;
            for(int i = 0; i < numColumns; i++) {
                maxLengths.add(0);
            }
        }

        if (numColumns != line.length) {
            throw new IllegalArgumentException();
        }

        for(int i = 0; i < numColumns; i++) {
            maxLengths.set(  i, Math.max( maxLengths.get(i), line[i].length() )  );
        }

        lines.add( Arrays.asList(line) );

        return this;
    }

    public void print(){
        System.out.println( toString() );
    }

    public String toString(){
        String result = "";
        for(List<String> line : lines) {
            for(int i = 0; i < numColumns; i++) {
                result += pad( line.get(i), maxLengths.get(i) + 1 );
            }
            result += System.lineSeparator();
        }
        return result;
    }

    private String pad(String word, int newLength){
        while (word.length() < newLength) {
            word += " ";
        }
        return word;
    }
}

Listing B

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

public class Columns {

    List<List<String>> lines = new ArrayList<>();
    List<Integer> maxLengths = new ArrayList<>();
    int numColumns = -1;
    String[] line;

    public Columns addLine(String... line) {

        this.line = line;
        learnNumOfColumnsOnce();
        ensureConsistantNumOfColumns();
        widenColumnsThatNeedIt();
        rememberLine();
        return this;
    }

    private void learnNumOfColumnsOnce() {
        if (numColumns == -1){
            numColumns = line.length;
            for(int i = 0; i < numColumns; i++) {
                maxLengths.add(0);
            }
        }
    }

    private void ensureConsistantNumOfColumns() {
        if (numColumns != line.length) {
            throw new IllegalArgumentException();
        }
    }

    private void widenColumnsThatNeedIt() {
        for(int i = 0; i < numColumns; i++) {
            maxLengths.set(  i, Math.max( maxLengths.get(i), line[i].length() )  );
        }
    }

    private void rememberLine() {
        lines.add( Arrays.asList(line) );
    }

    public void print(){
        System.out.println( toString() );
    }

    public String toString(){
        String result = "";
        for(List<String> line : lines) {
            for(int i = 0; i < numColumns; i++) {
                result += padWithSpaces( line.get(i), maxLengths.get(i) + 1 );
            }
            result += System.lineSeparator();
        }
        return result;
    }

    private String padWithSpaces(String word, int newLength){
        while (word.length() < newLength) {
            word += " ";
        }
        return word;
    }
}


texts:
Assignment Criteria
Create another version of the Hangman game, this time using Lists. The program should ask for the word to guess and the number of chances to be given.
It should then split the characters in the word into individual items in a list. The other player should then be allowed to guess characters in the word. The program should display correctly guessed characters and unknown characters in the same way as the previous Hangman game.

This a simple Hangman game in Python and I was just wondering if there was any code improvements that could be done with this. I can definitely see a few, but they're very minor changes (e.g. spaces can be removed as it's redundant and never really gets used.)
# ========== Variables ============ #
letter_bank = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

guessed = False  # Word has been guessed. (boolean)

spaces = ""      # Blanks
word_guess = []  # Placeholder
word_chars = []  # Characters in Word.

word = ""      # Word being guessed.
max_guess = None # Maximum amount of Guess.
cur_guess = 0 # Current count of Guesses.
# ================================= #
def findOccurences(s, ch):
    return [i for i, letter in enumerate(s) if letter == ch]

print('''
    Welcome to Hangman! Simplified version of the original Hangman.
''')

word = input("Please enter a word: ").lower()
max_guess = int(input("Maximum Guess: "))

for character in word:
    word_chars.append(character)
    if (character != " "):
        spaces += "_ "
        word_guess.append("-")
    else:
        spaces += ("  ")
        word_guess.append("  ")

print("\n" * 50)

print('''
    You are now ready to play.
''')

print("Word: %s. " % (spaces))
while (cur_guess < max_guess) and guessed == False:
    if (word.split() == (''.join(word_guess)).split()):
        guessed = True
        print('''
            You have successfully guessed the word!
        ''')
        break;

    letter_guess = input("Please enter your guess: ").lower()
    if (len(letter_guess) == 1):
        if (letter_guess not in letter_bank):
            print("You have already used that letter!") # Prints if the character is invalid or already used.
        else:
            if (letter_guess in word_chars):
                print("%s is in the word!" % letter_guess)
                letter_bank.remove(letter_guess)
                for each in findOccurences(word, letter_guess):
                    word_guess[each] = letter_guess
                print(''.join(word_guess))
            else:
                print(''.join(word_guess))
                print("%s is not in the word!" % letter_guess)
                letter_bank.remove(letter_guess)
                cur_guess += 1
    else:
        if (letter_guess == word):
            print('''
                You have successfully guessed the word!
            ''')
        else:
            print('''
                You have lost the game! :(
            ''')
            break;


texts: Find the maximum line length in a given TSV colum

texts:
I'm trying to write a function that given a TSV file will get the maximum line length found in a column. I currently have this (working) function. However, I feel that I am missing something as this solution feels poor compared to solutions I have seen to find the maximum length of a file:

max(open(filename), key=len)

Anyway, I would love some feedback and would love some tough feedback.

def get_longest_item_in_tsv_column(filepath, column):
    '''
    Returns the longest line in a given file.
    '''

    longest_item = None

    with open(filepath, 'r') as f:
        csv_reader = csv.reader(f,
                                delimiter='\t')

        for row in csv_reader:

            current_item_length = len(row[column])

            if current_item_length > longest_item:
                longest_item = current_item_length


texts:
In Java, there is no way I know of to wait for multiple events at the same time (see Stack Overflow). Since I would like to use that feature (similar to WaitForMultipleObjects() in the Win32 API), I decided to write my own event class that includes this feature. While the class is pretty straight-forward, thread synchronization always has some hidden pitfalls. I would like to uncover those, if any are present.

For some more specific questions:

Are there any possible deadlocks, race conditions, data races or other bugs present in the code?
Is the synchronization sufficient, or should bSignaled be made volatile?
Are there redundant checks or other things reducing the performance of the code?
Is there a library class that I have missed, offering the same functionality?

public class Event
{
    private boolean bSignaled = false;

    private static final Object anySignaler = new Object();

    /**
     * Wait for the event to signal. If the event has been signaled before,
     * return immediately.
     */
    public void await() throws InterruptedException
    {
        if (!bSignaled) {
            synchronized (this) {
                while (!bSignaled) {
                    this.wait();
                }
            }
        }
    }

    /**
     * Signal the event. This notifies all threads that are waiting for this
     * event to occur, as well as all threads that are waiting for any event.
     */
    public void signal()
    {
        bSignaled = true;
        sendNotify(this);
        sendNotify(anySignaler);
    }

    /**
     * Helper function that calls notifiyAll() inside a locked block.
     */
    private static final void sendNotify(Object lock)
    {
        synchronized (lock) {
            lock.notifyAll();
        }
    }

    /**
     * Return the signaled state of this event.
     */
    public boolean isSignaled()
    {
        return bSignaled;
    }

    /**
     * @see Event#awaitAll(Event[])
     */
    public static void awaitAll(Event ev0,Event ... events) throws InterruptedException
    {
        ev0.await();
        for (Event e: events) e.await();
    }

    /**
     * @see Event#awaitAll(Event[])
     */
    public static void awaitAll(List<Event> events) throws InterruptedException
    {
        for (Event e: events) e.await();
    }

    /**
     * Wait until all events have been signaled.
     */
    public static void awaitAll(Event[] events) throws InterruptedException
    {
            for (Event e: events) e.await();
    }

    /**
     * @see Event#awaitAny(Event[])
     */
    public static int awaitAny(Event ev0,Event ... events) throws InterruptedException
    {
        Event[] array = new Event[events.length+1];
        array[0] = ev0;
        if (events.length > 0) System.arraycopy(events,0,array,1,events.length);
        return awaitAny(array);
    }

    /**
     * @see Event#awaitAny(Event[])
     */
    public static int awaitAny(List<Event> events) throws InterruptedException
    {
        return awaitAny(events.toArray(new Event[events.size()]));
    }

    /**
     * Wait until any of the given events have been signaled. If any of the
     * events have already been signaled, return immediately.
     * @return the index of the event that was first found to be signaled.
     */
    public static int awaitAny(Event[] events) throws InterruptedException
    {
        int res = checkSignals(events);
        if (res < 0) {
            synchronized (anySignaler) {
                while ((res = checkSignals(events)) < 0) {
                    anySignaler.wait();
                }
            }
        }
        return res;
    }

    /**
     * Helper function to check if any of the events has been signaled.
     * @return the index of the first signaled event found,
     *         or -1 if no event was signaled.
     */
    private static int checkSignals(Event[] events)
    {
        int len = events.length;
        for (int i = 0; i < len; i++) {
            if (events[i].isSignaled()) return i;
        }
        return -1;
    }
}


texts: Given a series of characters from stdin, print their squared integer ASCII counterparts

texts:
This program in essence is extremely simple, however, it can be written in many different ways. I'm a beginner at C and I've written it in 5 different variations (mostly differing in the use of getchar over scanf, while over do while loops..).

Apart from readability and/or maintainability, is there any difference between these 5 code blocks (such as perhaps performance or efficiency, if we disregard the use of getchar over scanf)?

unsigned char d;

while (1)
    while(scanf("%c", &d), d != '\n') {
        printf("%d\n", d * d);
    }

do {
    scanf(" %c", &d);
    printf("%d\n", d * d);
} while (1);

while (1)
    while((d = getchar()) != '\n') { //could also be written as while(d = getchar(), d != '\n')
        printf("%d\n", d * d);
    }

while ((d = getchar())) {
    if(d == '\n')
        continue;
    printf("%d\n", d * d);
}

do {
    d = getchar();
    if(d == '\n')
        continue;
    printf("%d\n", d * d);
} while (1);


texts: Modified TextBox for forms generating SQL statements

texts:
An overview of what I've done:

I've inherited System.Windows.Forms.TextBox and added a few properties to help me out in creating forms that generate SQL statements.

I use to create a large function that would check for changes in the TextBox compared to a string. Then it would take text and concatenate it to a SQL statement. Now it's simple and easier to use.

I've added four properties:

A String property to hold the default string that the textbox is initially set to and will reset back if the text is left empty.
A String property to hold the text's associated SQL statement.
A Boolean to check if the text has changed from the default.
Finally, an Integer to hold an ID if there is a reason to need one, such as saving and loading text from a file by the ID.

I have not fully implemented the new textbox in my code, but I am working on it.

It may only be slightly modified, but it should cut down my code from 500+ lines of code down to less than +-30 if ran in a for-loop.

SQLTextBox.vb

Public Class ModifiedTextBox
    Inherits System.Windows.Forms.TextBox

    Private _strDefaultText As String
    Private _strSqlText As String
    Private _nID As Integer
    Private _bModified As Boolean = False

    Property ID()
        Set(nID)
            _nID = nID
        End Set
        Get
            Return _nID
        End Get
    End Property

    Property TextModified()
        Set(bModified)
            _bModified = bModified
        End Set
        Get
            Return _bModified
        End Get
    End Property

    Property SqlText()
        Set(strSqlText)
            _strSqlText = strSqlText
        End Set
        Get
            Return _strSqlText
        End Get
    End Property

    Property DefaultText()
        Set(strDefaultText)
            _strDefaultText = strDefaultText
            Me.Text = _strDefaultText
        End Set
        Get
            Return _strDefaultText
        End Get
    End Property

End Class

I've pulled an excerpt from my code. It's not much, but here is the new textbox vs the old one.

In the SQL text, I have something like ""Material Type"" in('INSERTTEXT').
SQLTextBox.Modified gets set when the user leaves the textbox (set to false b default).

'This should run every new textbox (untested)
For i As Integer = 0 To Me._icControls.txtMain.Length - 1
    If Me._icControls.txtMain(i).Modified = True Then
        sqlWhere += " AND " + Me._icControls.txtMain(i).SqlText
        Replace(sqlWhere, "INSERTTEXT", Me._icControls.txtMain(i).Text)
    End If
Next

'Old, long way around where I had split up
'the textboxes into 7 groups they belonged too.
If Me._icControls.txtMaterial(0).Text.ToString() <> DefaultStrings.Material(0) Then
    sqlWhere += " AND ""Material Type"" in('" + Me._icControls.txtMaterial(0).Text.ToString() + "')"
End If

If Me._icControls.txtMaterial(4).Text.ToString() <> DefaultStrings.Material(4) Then
    sqlWhere += " AND ""Grade"" in('" + Me._icControls.txtMaterial(4).Text.ToString() + "')"
End If

If Me._icControls.txtMaterial(5).Text.ToString() <> DefaultStrings.Material(5) Then
    sqlWhere += " AND ""PIW"" in('" + Me._icControls.txtMaterial(5).Text.ToString() + "')"
End If

I went from 200 lines of code to 6, with a minor change. That does not include the lines spent setting up the default text.

Let me know what you think of this. I'm not sure if it's really anything someone could use, but it's been very useful to me.


texts: Connection to a database, do I need to create a new one and close it everytime?

texts:
I currenctly have a class which does several requests to a database with several methods (called from main method) sharing this pattern :

public int getSomething(String id, File file) {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    int lines = 0;

    try {
        conn = openConnection();
        ps = conn.prepareStatement(SQL_QUERY.replace("?", id));
        ps.setFetchSize(1500);
        rs = ps.executeQuery();

        lines += nnpw.writeInFile(file, rs);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        close(rs, ps, conn);
    }
    return lines;
}

The method openConnection() is in the main class and looks like this :

protected Connection openConnection() throws SQLException, ClassNotFoundException {
    Class.forName(jdbcParams.getString("jdbc.driver"));
    Connection connect;
    connect = DriverManager.getConnection(jdbcParams.getString("jdbc.url"), //$NON-NLS-1$
            jdbcParams.getString("jdbc.username"), //$NON-NLS-1$
            jdbcParams.getString("jdbc.password")); //$NON-NLS-1$
    return connect;
}

Would it be better if I had a Connection parameter in the main class, which I would open and close like this, and modify the close(rs, ps, conn) from above to close(rs, ps) ?

public MainClass {
    Connection conn;

    public static void main(String[] args) {
        try {
            int lines = 0;
            DBExtract ex = new DBExtract();
            ...
            conn = openConnection()
            lines += ex.getSomething("1", file, conn);
            lines += ex.getSomethingElse("1", file, conn);
            lines += ex.getSomethingDifferent("1", file, conn);
            conn.close()
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}


texts: Cythonic Laplacian solving on a 3D regular grid

texts:
I have followed to official Cython for NumPy users to make a Laplacian solver on a 3D regular grid with Dirichlet conditions.

Right now I'm happy with the results it returns, but I'm wondering if there was a more efficient way to code this, especially since the tutorial I have followed is about 10 years old. I have very limited knowledge of C and I'm not sure if the data types (ctypedef) are properly chosen here and/or would have a significant impact on performance. I have tried types my indexes variables as unsigned int in different ways but I ended up giving up as I'm not really sure if it is relevant.

Also, I'm happy with any general coding style and good practices advice.

The Python code that calls my Cython function is inside a class and looks like this:

def _solve_laplacian(self):
    init = np.zeros_like(self.domain, float)
    init[np.logical_not(self.border)] = 1
    log.info("Solving Laplacian...")
    laplace_grid, iterations, max_error = laplace_solver(
        self.domain_idx_i,
        self.domain_idx_j,
        self.domain_idx_k,
        init,
        self.laplace_tolerance,
        self.laplace_max_iter,
        self.spacing)
    log.debug(
        f"Laplacian: {iterations} iterations, max_error = {max_error}")
    self.cropped_laplace_grid = laplace_grid
    self.laplacian_iterations = iterations
    self.laplacian_max_error = max_error

and here is the actual cython function:

import numpy as np
cimport numpy as np
cimport cython

ctypedef np.float64_t DTYPE_FLOAT
ctypedef np.int_t DTYPE_INT

# dirty fix to get rid of annoying warnings
np.seterr(divide='ignore', invalid='ignore')

@cython.boundscheck(False)
@cython.wraparound(False)
def solve_3D(np.ndarray[DTYPE_INT, ndim=1] domain_idx_i,
             np.ndarray[DTYPE_INT, ndim=1] domain_idx_j,
             np.ndarray[DTYPE_INT, ndim=1] domain_idx_k,
             np.ndarray[DTYPE_FLOAT, ndim=3] init,
             DTYPE_FLOAT tolerance,
             DTYPE_INT max_iterations,
             np.ndarray[DTYPE_FLOAT, ndim=1] spacing):
    cdef np.ndarray[DTYPE_FLOAT, ndim=3] laplace_grid = np.copy(init)
    cdef np.ndarray[DTYPE_FLOAT, ndim=3] prev_laplace_grid = np.copy(
        laplace_grid)
    cdef DTYPE_INT iteration = 0
    cdef DTYPE_FLOAT max_error = 1.0
    cdef DTYPE_INT n_points = len(domain_idx_i)
    cdef DTYPE_INT i, j, k, n
    cdef DTYPE_FLOAT error
    cdef DTYPE_FLOAT value
    cdef DTYPE_FLOAT hi, hj, hk, hi2, hj2, hk2, factor

    hi, hj, hk = spacing
    hi2, hj2, hk2 = spacing ** 2

    factor = (hi2 * hj2 * hk2) / (2 * (hi2 * hj2 + hi2 * hk2 + hj2 * hk2))

    while max_error > tolerance and iteration < max_iterations:
        iteration += 1
        prev_laplace_grid[:] = laplace_grid
        for n in range(n_points):
            i = domain_idx_i[n]
            j = domain_idx_j[n]
            k = domain_idx_k[n]
            value = \
                (
                    (laplace_grid[i + 1, j, k] +
                     laplace_grid[i - 1, j, k]) / hi2 +
                    (laplace_grid[i, j + 1, k] +
                     laplace_grid[i, j - 1, k]) / hj2 +
                    (laplace_grid[i, j, k - 1] +
                     laplace_grid[i, j, k + 1]) / hk2
                ) * factor
            laplace_grid[i, j, k] = value
        max_error = np.nanmax(
            np.abs(
                (prev_laplace_grid[domain_idx_i, domain_idx_j, domain_idx_k] -
                 laplace_grid[domain_idx_i, domain_idx_j, domain_idx_k]) /
                prev_laplace_grid[domain_idx_i, domain_idx_j, domain_idx_k]))
    return laplace_grid, iteration, max_error

If you're interested in the complete Python package this is part of, it is available here and is quite ugly right now. I'm trying to improve it so I'm not ashamed of it anymore.


texts: Creating lists of events (pitches, velocities, delta-times, durations) from a MIDI track

texts:
I am trying to understand good design patterns in Python and I cannot think of a way to break this huge function into smaller parts without making the code cluttered, overly complex or plain ugly.

I didn't want to clutter my question by posting the whole file. This function itself is already very large, but the class has only two methods: parse_midi() and generate_midi(file_name, file_length).

pitches, velocities, deltas, durations, and intervals are all MarkovChain objects. MarkovChain is a simple class with methods: add_event(event), generate_markov_dictionary(), and get_next_event(previous_event). MarkovChain.src_events is a list of events to generate the Markov chain from. It is a simple implementation of first order Markov chains.

def parse_midi(self):
    # on_notes dictionary holds note_on events until corresponding note_of event is encountered
    on_notes = {}
    time = 0
    previous_pitch = -1
    tempos = []
    delta = 0
    for message in self.track_in:
        time += message.time
        delta += message.time
        # There are also MetaMessages in a midi file, such as comments, track names, etc.
        # We just ignore them
        if isinstance(message, mido.Message) and message.type in ["note_on", "note_off"]:
            # some midi files use note_on events with 0 velocity instead of note_oof events
            # so we check if velocity > 0
            if message.velocity > 0 and message.type == "note_on":
                on_notes[message.note] = time
                self.pitches.add_event(message.note)
                self.velocities.add_event(message.velocity)
                self.deltas.add_event(delta)
                delta = 0
                if previous_pitch == -1:
                    self.intervals.add_event(0)
                else:
                    self.intervals.add_event(message.note - previous_pitch)
            else:
                # KeyError means note_off came without a prior associated note_on event!"
                # Just ignore them
                with ignored(KeyError):
                    self.durations.add_event(time - on_notes[message.note])
                    del on_notes[message.note]

            previous_pitch = message.note
        # Tempo might be many tempo changes in a midi file, so we store them all to later calculate an average tempo
        elif message.type == "set_tempo":
            tempos.append(message.tempo)
        elif message.type == "time_signature":
            self.time_signature = self.TimeSignature(message.numerator, message.denominator,
                                                     message.clocks_per_click, message.notated_32nd_notes_per_beat)
    # some tracks might be aempty in a midi file. For example they might contain comments as track name, and no note events
    if len(self.pitches.src_events) == 0:
        print("There are no note events in track {}!\n"
              "The file has {} tracks. Please try another one.".format(self.selected_track, self.num_tracks))
        exit(1)
    # a midi file might not contain tempo information at all. if it does, we calculate the average
    # else we just assign a default tempo of 120 bpm
    try:
        self.average_tempo = int(sum(tempos) / len(tempos))
    except ZeroDivisionError:
        self.average_tempo = mido.bpm2tempo(120)


texts:
I am trying to write an MVC based application from scratch using Java 8 and Swing... I am having some difficulties with this.

I want to know if I am going the correct way about this...

My controller code is:

public class Controllerv2 {
private final Map<String, View> views = new HashMap<>();
private final Map<String, Command> commands = new HashMap<>();

private final ModelContainer model = new ModelContainer(this);

public void addView(String key, View view) {
    views.put(key, view);
}

public View getView(String key) {
    return views.get(key);
}

public void showView(String key) {
    getView(key).showForm();
}

public void addCommand(String commandString, Command cmd) {
    commands.put(commandString, cmd);
}

public void executeControllerCommand(String commandString) {
    commands.get(commandString).execute();
}
}

public abstract class View {
protected final JDialog dialog = new JDialog();
protected final GUIAction guiAction = new GUIAction();
protected final Controllerv2 controls;

Views are subclassed from this class:

public View(Controllerv2 suppliedController) {
    this.controller = suppliedController;
}
// Fires up the form
protected abstract void initComponents();

// Package up the fields into an object of type T and return
public abstract <T> T readFields();

// Self explanatory functions
public void showForm() {dialog.setVisible(true);}
public void hideForm() {dialog.setVisible(false);}

// For fields that need updating
public abstract void updateFields(String[] msg);
}

This is an example of a concrete View:

public final class VBasexLoginR extends View {
private JButton connectButton;
private JLabel connectionLabel;
private JTextField hostField;
private JLabel hostLabel;
private JLabel passwordLabel;
private JButton pingButton;
private JTextField portField;
private JLabel portLabel;
private JPasswordField pwField;
private JLabel titleLabel;
private JTextField uidField;
private JLabel userId;

public VBasexLoginR(Controllerv2 c) {
    super(c);
    initComponents();
}

@Override
protected void initComponents() {// Boilerplate to setup the form}

@Override
public BaseXCredentials readFields() {
    return new      BaseXCredentials(hostField.getText(),portField.getText(),uidField.getText(),pwField.getPassword());
}

@Override
public void updateFields(String[] msg) {
    connectionLabel.setText(msg[0]);
}
}

Am I going in the right direction with this?

Also, I think I may need different models, one for running queries on BaseX and then ones for working with the results. Thus far I have...

public class ModelContainer {
private final Map<String, Model> models = new HashMap<>();
private final Map<String, ModelCommand> commands = new HashMap<>();
private final Controllerv2 controller;

ModelContainer(Controllerv2 suppliedController) {
    this.controller = suppliedController;
}

public void addModel(String key, Model model) {
    models.put(key, model);
}

public Model getModel(String key) {
    return models.get(key);
}

public void addCommand(String key, ModelCommand cmd) {
    commands.put(key, cmd);
}

public void executeModelCommand(String key) {
    commands.get(key).execute();
}
}

Views can be got at through the getView method in controls

Is this correct or is this overkill?

EDIT -- Taking into account Mat's Mug response, changed the code to reflect the naming conventions suggested.


texts: c++ is it worth preprocessor optimization for for loops while i < 1

texts:
I'm writing some code to take high precision timings of a function call

for (int i = 0; i < iterations; i++) {
    beginTime = high_resolution_clock::now();

    CallFunc(functionPtr, otherParamaters ...); // inline function call to do the timed function

    endTime = high_resolution_clock::now();
    elapsedTime = duration_cast<duration<double>>(endTime - beginTime);
    timings.push_back(elapsedTime.count());
}

However some of the functions I'm timing run so fast the clock can't pick them up, it ends up just writing a load of 0s
I Had the idea to do several repetitions of the function call per timing, to try to get a numerical time I could then divide down past the resolution of the clock, but I don't want to penalize the accuracy of the timing for functions that don't need these repetitions
My solution was to use preprocessor #ifs

for (int i = 0; i < iterations; i++) {
    beginTime = high_resolution_clock::now();

#if repetitions > 1
    for (int i = 0; i < repetitions; i++) {
#endif
        CallFunc(functionPtr, otherParamaters ...); // inline function call to do the timed function
#if repetitions > 1
    }
#endif
    endTime = high_resolution_clock::now();
    elapsedTime = duration_cast<duration<double>>(endTime - beginTime);
    timings.push_back(elapsedTime.count());
}

My question is, is this kind of optimization silly? Is the compiler likely to do this for me anyway?
EDIT: repetitions is a const int


texts: Project Euler Problem #7 in Python (10001st prime number)

texts:
I have managed to solve the 7th Project Euler problem, however I think it can be improved by a lot, I am by no means a professional programmer or even consider myself really good at it. Any improvements / suggestions would be really helpful.
Problem statement:

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?

This is my solution.
counter = 2
n = 10001
for i in range(3, 1000000, 2):
 k = 1
 while k < i:
  k += 2
  if i % k == 0:
   break
  if k + 2 == i:
   counter += 1
  if counter == n:
   print(i)
   raise ZeroDivisionError

The program does skip 2 and 3, in an attempt of mine to make it faster. At the end I raise an error in order to stop the program from looping.


texts:
What do you think about this code? I'm learning Python and I made this tool to code a plain text or decode it!

inp = input('Input the text you want to code:\n')
inp = inp.lower()

key = int(input('Input the key you want to use from 2 to 25:\n'))
def rot13(input,key): #Function to code a text with caeser chyper.
    if key > 25:
        key = 25
    elif key < 2:
        key = 2
    finaltext = ''
    for letter in input:
        if letter.isalpha():
            num = ord(letter)
            if (num + key) > 122: #If the final number is greater than 122..
                x = (num + key) - 122
                finaltext += chr(x + ord('a') - 1)
            elif((num + key <= 122)):
                finaltext += chr(num + key)
        else:
            finaltext += letter
    print(finaltext)

rot13(inp,key)


texts: Find the longest subarray with sum less than K

texts:
The problem consist of finding the longest contiguous subarray with a sum less than a given integer K.

The input data are:

K - the max sum
array - an array of integers

The algorithm I developed:

head = tail = 0

- while the tail is less than the length of the array
   - increment the tail and update the sum
   - if the sum go over the K, increment the head until the sum is less than K
   - while incrementing the tail check if we have a new max_length

The Python code:

def length_max_subarray(array, K):
    head, tail = 0, 0
    length = 0
    current_sum = 0
    while(tail<len(array)):
        if current_sum + array[tail]<=K:
            current_sum += array[tail]
            tail+=1
            if tail-head > length:
                length = tail-head
        else:
            current_sum -= array[head]
            head+=1

    return length

My assumption is "this code is \$O(N)\$" because:

The worst case is when all elements are larger than K. In that case the while loop will increment the head and the tail successively so the number of iterations is \$2*N\$.

Is it true? If not, what's the complexity of this code?


texts: Convert a numeric string to number but without python's built in function

texts:
I'd like to get a code review and some insights of whether I chose a good way to do this. What would other, clever ways look like.

"""
Convert numeric string to number withoutusing python's built in functions.
"""
dec_places = {6:100000, 5:10000, 4:1000, 3:100, 2:10, 1:1}
char_digit = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5,  '6':6, '7':7, '8':8,  '9':9}

def str2int(num_str):
    iter = len(num_str)
    number = 0
    for char in num_str:
        number += (char_digit[char] * dec_places[iter])
        iter -= 1
    return number

print(str2int('623297'))


texts: Saving and uploading images in a database

texts:
I am working on a small method that saves uploaded images and records the images in a database.

public function setEventImages($event_id){
            foreach($_FILES['event-images']['tmp_name'] as $tmp_name){
                $imgName = $this->imgPath . $this->random_name . $_FILES['event-images']['name'];
                move_uploaded_file($tmp_name, $imgName);
                $stmt = $this->dbh->prepare("INSERT INTO adrenaline_junkies_uk_event_images (event_image_name, event_id) VALUES (?,?)");
                $stmt->bindParam(1, $imgName, PARAM_STR);
                $stmt->bindValue(2, $event_id, PARAM_INT);
                $stmt->execute();
            }
        }

How can this be made more efficient?


texts: Parsing HTML, XML into a hash map of products

texts:
I'm working on a simple parser that is supposed to extract hash maps representing vinyl records from web pages (online stores) and XML files. The goal is to have a parser that I can easily run with multiple threads over a ~8 MB XML and a ~2 MB HTML file to read products into a relational database.

I know the relational database will be its own nightmare to marshal things into and to update, but learning how I can marry Clojure to a traditional database is part of my fun.

The initial parser seems to work reasonably well, but my grasp of idiomatic Clojure and my Clojure vocabulary are rudimentary at best. Do you have any suggestions?

Source on GitHub

The result of the doseq there is:

{:artist Lantlôs, :title Melting Sun, :price 12.99}
{:artist Alcest, :title Shelter, :price 12.99}
{:artist Alcest, :title Opale, :price 8.99}
{:artist Duncan Evans, :title Lodestone, :price 14.99}
{:artist Empyrium, :title Dead Winter Ways, :price 9.99}
{:artist Falkenbach, :title Asa, :price 14.99}
{:artist Negura Bunget, :title Gînd a-prins, :price 8.99}
{:artist Sol Invictus, :title Mr Cruel, :price 8.99}
{:artist LowCityRain, :title LowCityRain, :price 13.99}
{:artist Vàli, :title Forlatt, :price 14.99}
{:artist Vàli, :title Skogslandskap, :price 14.99}
{:artist Nhor, :title Within The Darkness Between The Starlight, :price 24.99}

I'm only working on one single parser (the one for Prophecy Productions in that core.clj file) right now. Once I have multiple parsers ready, I'll have to find a good way to split the project into multiple files and have some sort of centralized reader that takes the hash-maps and marshals them into a database. But I'll bug people here about that when I get there.


texts:
I have a function below that does the following uses a bunch of smaller CRUD operations which I call create, retrieve (instead of read), update, delete. Because this function does a bit of everything it can be hard to name it.

Here's a bit about its behavior:

pass in array of redirects (objects with url, and path properties)
retrieves all existing redirects
checks to see if requesting redirect path exists
if existing redirect with path exists and url is the same returns existing
if existing redirect with path exists updates redirect
if existing redirect with path does not exist creates new redirect

Here are some possible candidates:

retrieveAllRedirectsUpdateExistingRedirectsCreateNewRedirectsDoNothingForRedirectsWithNoChange
retrieveAllUpdateExistingCreateNewRedirects
retrieveUpdateCreateRedirects
ensureRedirectsExist
ensureRedirects
overwriteRedirects // implies will delete redirects not passed to it
createRedirects
redirects

Here's the function:

Shopify.prototype.ensureRedirects = function(redirects){
  return this.retrieveAllRedirects().then(function(existingRedirects){
    return Promise.map(redirects, function(redirect){
      return Promise.resolve(existingRedirects).then(_).call("findWhere", {
        "path": redirect.path,
      }).then(function(match){
        if(match && match.url == redirect.url) return match
        if(match) return this.updateRedirect(match.id, redirect)
        return this.createRedirect(redirect)
      }.bind(this))
    }.bind(this))
  }.bind(this))
}

What naming convention lends itself to the most flexibility and follows the best pattern?

Other functions that I have in this library include but aren't limited to:

retrieveRedirects (paginated)
retrieveRedirectsCount
retrieveAllRedirects (all pages)
createRedirect
updateRedirect

This also begs the question should this function above be createRedirects as an alias of createRedirect that detects argument type object v.s. array and creates the redirects accordingly, making the createRedirect function more versatile to handle argument types? Then what do you name the function and argument? Convention for naming a function or variable as both plural and singular


texts:
I've translated this Java code into Delphi code:

unit Trampoline;

interface

type
  ITrampoline<T> = interface
    function Get: T;
    function Run: ITrampoline<T>;
    function Execute: T;
  end;

  TTrampoline<T> = class(TInterfacedObject, ITrampoline<T>)
  public
    function Get: T; virtual;
    function Run: ITrampoline<T>; virtual;
    function Execute: T; virtual; final;
  end;

  TFactorial = class(TTrampoline<integer>)
  private
    fsum, fn: integer;
  public
    constructor Create(n, sum: integer);
    class function Factorial(n, sum: integer): ITrampoline<Integer>; static;
    function run: ITrampoline<Integer>; override;
  end;

implementation

uses System.Generics.Defaults;

function TTrampoline<T>.Run: ITrampoline<T>;
begin
  Result:= nil;
end;

function TTrampoline<T>.Get: T;
begin
  Result:= default (T);
end;

function TTrampoline<T>.Execute: T;
var
  Comparer: IEqualityComparer<T>;
  Trampoline: ITrampoline<T>;
begin
  Trampoline:= Self;
  Comparer:= TEqualityComparer<T>.Default;
  while Comparer.Equals(Trampoline.get, default (T)) do begin
    Trampoline:= Trampoline.run;
  end;
  Result:= Trampoline.get;
end;

type
  TDoneFactorial = class(TFactorial)
    function get: integer; override;
  end;

constructor TFactorial.Create(n, sum: integer);
begin
  fn:= n;
  fsum:= sum;
end;

class function TFactorial.Factorial(n, sum: integer): ITrampoline<Integer>;
begin
  if (n <= 1) then begin
    Result:= TDoneFactorial.Create(n, sum);
  end else begin
    Result:= TFactorial.Create(n, sum);
  end;
end;

function TDoneFactorial.get: integer;
begin
  Result:= fsum;
end;

function TFactorial.run: ITrampoline<Integer>;
begin
  Result:= Factorial(fn - 1, fsum * fn);
end;

end.

Usage:

procedure TForm5.Button1Click(Sender: TObject);
var
  Outcome: Integer;
begin
  Outcome:= TFactorial.Factorial(StrToInt(Edit1.Text), 1).Execute;
  Label2.Caption:= IntToStr(OutCome);
end;

It runs nicely, in all the iterations of the execute method the stack pointer does not move and hence it will not generate a stack overflow no matter how many deep the recursion goes.

It is rather inefficient though because of:

The implicit try - finally guarding the interface variable
The constant creation of new structures on the heap.

Is there a more efficient way to do this?

Never mind the fact that factorials are a stupid example for recursion.  I know recursion is only really useful with trees.


texts:
As part of an android app, I've written a simple wrapper that makes requests to an api and fetches stuff.

import android.app.Activity
import android.util.Log
import android.widget.Toast
import com.github.kittinunf.fuel.core.Parameters
import com.github.kittinunf.fuel.httpGet
import com.github.kittinunf.fuel.json.responseJson
import com.github.kittinunf.result.Result
import com.google.gson.Gson

data class Xkcd(val id: Int, val content: String, val link: String, val title: String)

class XkcdClient(private val main: Activity) {
    private val API = "https://279fbce3.ngrok.io"

    fun search(p: Parameters, callback: (Array<Xkcd>) -> Unit) {
        makeRequest("$API/search", p, callback)
    }

    private inline fun <reified T> makeRequest(url: String, p: Parameters, crossinline callback: (T) -> Unit) {
        buildPath(url, p)
            .httpGet()
            .responseJson { _, _, result ->
                when (result) {
                    is Result.Failure -> {
                        Log.i("failed", "request failed")
                        main.runOnUiThread {
                            Toast.makeText(
                                main,
                                "Request Failed!",
                                Toast.LENGTH_LONG
                            ).show()
                        }
                    }
                    is Result.Success -> {
                        val json = result.get().obj()
                        Log.i("json", json.toString())
                        val res = deserialize<T>(json.get("results").toString())
                        main.runOnUiThread { callback(res) }
                    }
                }
            }
    }
}

inline fun <reified T> deserialize(content: String): T {
    return Gson().fromJson(content, T::class.java)
}

fun buildPath(url: String, params: Parameters): String {
    var url = url
    if (params.isNotEmpty()) {
        url += "?"
    }

    for ((p, v) in params) {
        url += "$p=$v&"
    }
    return url.substring(0, url.lastIndex)
}

It works as I want it to. As such, I'm looking for some advice on how I can make it more idiomatic/elegant.

Just FYI: I've written the buildPath myself, as the http library I'm using (kittinuf.fuel) has a bug in its parameter setting method. When it's fixed, I'll be switching to its (hopefully correct) implementation. My method has at least one known bug in it, where if the base url has a trailing slash, it will return a url with double slashes. To avoid getting into all hairy edges cases, I've made sure my hardcoded base url is fine and stripped of a trailing slash.


texts: Find all words that satisfy unknown letters (Hangman)

texts:
I have been working on a function which might be used to solve a word game like Hangman or "Wheel of Fortune".

Basically, I wish to search from a very large WORD_LIST (>1 million unique entries) for any word which satisfies the provided letters in the word search.

An example of this might be if search is "A??LE", the resulting list will contain  apple, ankle, ...

But that technically, if a letter is already provided/revealed, then it cannot also be one of the blanks eg; search= "HANG???" might return hangout, hangers but not hangman because the A/N has already been guessed.

Mainly I'm wondering if the string search speed can be increased, or if a more elegant (RegEx?) method of searching might give me faster results without losing accuracy.

def words_like(search, without_letters='', preclude_revealed_letters=True):
    if len(search) < 1:
        return []

    search = search.lower()
    without_letters = without_letters.lower()
    # Find indices of letters and blanks
    letters = [i for i, x in enumerate(list(search)) if x != "?"]
    blanks = [i for i, x in enumerate(list(search)) if x == "?"]

    if preclude_revealed_letters:
        # If a letter has been revealed, it can't also be one of the blanks
        without_letters = set(without_letters+''.join([x for x in search if x != "?"]))

    # Search our word-list for all matching "revealed" letters
    possible_words = []

    for w in WORD_LIST:
        if len(w) != len(search):
            continue
        for i in letters:
            if search[i] != w[i]:
                break
        else:
            possible_words.append(w)
    # Then remove all that use forbidden letters in the blanks
    without_possibles = []

    for w in possible_words:
        for i in blanks:
            if w[i] in without_letters:
                break
        else:
            without_possibles.append(w)
    return without_possibles


texts: Simple decorator for creating and managing a database cursor

texts:
I'm working on a simple decorator that creates and manages a database cursor.  The goal is to 'inject' the cursor as the first argument of the function, but not expose it to the caller.

Usage:

import psycopg2

@needsNewCursor
def findItem(cursor, item_id):
    cursor.execute('SELECT name FROM items WHERE id = %s', [item_id])
    item_result = cursor.fetchone()
    # ...
    return item

# caller only needs to know about the ID
findItem(1234)

Decorator:

def needsNewCursor(func):
    def decorator(*args, **kargs):
        print 'Creating new cursor'
        # This is slightly different in the final code, but I'm only
        # concerned about how I'm dealing with decorators, at the moment
        cursor = createDefaultCursor()
        if cursor:
            with cursor:
                # Pass the cursor in as the 1st param
                return func(cursor, *args, **kargs)

        # Give the function a chance to deal with fails
        return func(None, *args, **kargs)

    # QUESTION: Is this enough?
    decorator.__name__ = func.__name__
    return decorator

Is this a good approach?


texts: Factory pattern for creating sub classes derived from interface with generic type

texts:
Would like to know if the factory pattern I've implemented for my stat library is the correct way to go. I have an interface IPlayerStatsManager where the type parameter is an interface as well (IPlayerStatsModel). The IPlayerStatsManager is an interface that lists the common operations that can be performed on any class that implements IPlayerStatsModel. I've only completed the implementation for basketball and it seems to work correctly but would like to know if the way I currently have it is the most efficient way. Here's the code (some of the implementation removed for brevity)

Context

public interface IPlayerStatsModel
{
    string type {get; set;}
}

// concrete implementation
public class  BasketballPlayerStats : IPlayerStatsModel
{
    // various class members with getters and setters
}

public interface IPlayerStatsManager<T> where T : IPlayerStatsModel
{
    Task<T> GetPlayerGameStats(....);

    Task<List<T>> GetPlayersGameStats(...);

    // insert and update methods
}

//concrete implementation
public class BasketballPlayerStatsManager : IPlayerStatsManager<BasketballPlayerStats>
{
    public BasketballPlayerStatsManager(DbContext context)
    {
    }

    public async Task<BasketballPlayerStats> GetPlayerGameStats(...)
    {
    }
}

Factory

//Factory class
public class PlayerStatsFactory<IPlayerStatsManager>
{
    public static IPlayerStatsManager Create(DbContext context, int sportType)
    {
        if (sportType == (int)Utils.SportType.Basketball)
        {
             return (IPlayerStatsManager)Activator.CreateInstance(typeof(BasketballPlayerStatsManager));
        }
        return default(IPlayerStatsManager);
     }
}

I feel like there might be a better way but I'm not sure what that would look like. Any pointers would be greatly appreciated.


texts: How to increase the efficiency of DLA algorithm?

texts:
The algorithm:

Place seed at the center of the canvas.
Release a random walker from the edge.
Random walker sticks to the neighboring sites of the seed/previous points.
Repeat N(particles) times.

For a 500x500 matrix with 50k iterations, it would easily take one full day to compute. How to reduce the computation time drastically?

Why 50k particles, cause it's a part of the assignment!

Logically program is correct.

I tried profiling, it didn't tell me a whole lot. The while loop is causing the issue? Any suggestions to improve the efficiency of my code?

import time
import numpy as np
import random
import matplotlib.pyplot as plt
from numba import jit, cuda, prange

#from numba import roc
starttime = time.time()
arr = [h,w] = [500,500] #track of height and width of canvas
particles = 50000
sticking_coeff = 0.5
canvas = np.zeros((h, w)).astype(int) #the blank n * n matrix
canvas[h//2,w//2] = 1 #make center element is 1
#// to get the floor value
stick = []
stick.append([h//2 + 1, w//2])#below 1
stick.append([[h//2 - 1, w//2]])#above 1
stick.append([h//2, w//2 + 1])#right of 1
stick.append([h//2, w//2 - 1])#left of 1

#@jit(nopython=True, parallel=True)
#@roc.jit(device=True)
#@numba.jit()
@jit(cache=True)
def walk(A, B, canvas):# A: row B: Column
    while True:
        #print('while')
        x = np.random.randint(4)#0: row 1: column
        if x == 0:#forward option
            A += 1
            #print('A+')
        elif x == 1:
            B += 1
            #print('B+')
        elif x == 2:
            A -= 1 #reverse option
            #print('A-')
        else:
            B -= 1
            #print('B-')

        #take care of overflow
        if A < 0:
            A = 0
            #print('A=0')
        elif B < 0:
            B = 0
            #print('B=0')
        if A >= h:
            A -= 1
            #print('A-1')
        elif B >= w:
            B -= 1
            #print('B-1')

        positi = [A , B]
        if positi in stick:
            if np.random.rand() < sticking_coeff:
                for site in [[positi[0] + 1, positi[1]],
                            [positi[0] - 1, positi[1]],
                            [positi[0], positi[1] + 1],
                            [positi[0], positi[1] - 1]]:
                    if site not in stick:
                        stick.append(site)
                canvas[positi[0] , positi[1]] = 1
                break  # <-- Also, this is require, I think
            else:
                continue

    return canvas

for i in prange(particles):

        print('particle ',i+1)
        selec = random.sample(set(['A','B','C','D']),1)
        #pos1 = randrange(0, len(arr))
        pos = np.random.randint(0, len(arr))
        print(selec)

        if selec == ['A']:
            #arr[:,0]#first column
            #arr[pos,0] = 1
            walk(pos,0,canvas)

        elif selec == ['B']:
            #arr[:,-1]#last column
            #arr[pos,-1] = 1
            walk(pos,-1,canvas)

        elif selec == ['C']:
            #arr[0,:]#first row
            #arr[0,pos] =1
            walk(0,pos,canvas)

        else:
            #arr[-1,:]#last row
            #arr[-1,pos] = 1
            walk(-1,pos,canvas)
plt.matshow(canvas)
plt.savefig("rand_walk.png",dpi=2000)
print('That took {} seconds'.format(time.time() - starttime))


texts:
I have made a password reveal feature, however the code is duplicated. Essentially all I want to be able to improve the code, however I'm not exactly sure how I could do this, all I know is it would consist of some form of loop.

I would go straight to jQuery but there is no need in 2018.

This is my functionality markup for my HTML (it’s the same for the login page and modal):

<form action="/login" method="post">

        Username :
        <input class="input-field width-100" type="text" autocomplete="username" name="username" placeholder="Enter Your Username">

        Password :
        <input class="input-field width-100 password" data-js="viewShowPassword" type="password" autocomplete="current-password" name="password" placeholder="Enter Your Password">

            <input type="checkbox"/> Remember Me

            Show Password

        <button class="submit width-100 input-field text-white background-red--light" style="padding: 5px">Login</button>

</form>

And this is my JavaScript, which shows both the login page and login modal code to demonstrate what I have so far:

document.addEventListener("DOMContentLoaded", function(event) {

    var modalShowPassword = document.querySelector("[data-js=modalPasswordReveal]");
    var modalPassword = document.querySelector("[data-js=modalPassword]");

    if(modalShowPassword || modalPassword) {
        modalShowPassword.addEventListener("click", function (){
            if (modalPassword.type === "password") {
                modalPassword.type = "text";
            } else {
                modalPassword.type = "password";
            }
        });
    }

    var viewShowPassowrd = document.querySelector("[data-js=viewPasswordReveal]");
    var viewPassword = document.querySelector("[data-js=viewShowPassword]");

    if( viewShowPassowrd || viewPassword) {
        viewShowPassowrd.addEventListener("click", function (){
            if (viewPassword.type === "password") {
                viewPassword.type = "text";
            } else {
                viewPassword.type = "password";
            }
        });
    }
});

FYI I'm fairly new to the world of JavaScript so I'm not very good.


texts:
This question is taken from Leet code.

  Given an array nums of n integers and an integer target, find three
  integers in nums such that the sum is closest to target. Return the
  sum of the three integers. You may assume that each input would have
  exactly one solution.

  Given array nums = [-1, 2, 1, -4], and target = 1.

  The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

I need feedback on my solution from programming interview perspective (where they rate you on quality of solution).

My first solution is this (and preferred)

scala> ((List(-1,2,1,-4).combinations(3).map(_.sum) map (sum => (sum,Math.abs(1-sum))) toList) sortWith(_._2 < _._2)).head._1
res166: Int = 2

But I expect interviewer might ask me to implement combinations (and use one provided by library) . So I implemented the same like this

def combinations(l: List[Int], c: Int): List[List[Int]] = {
    if (c == 1) { l map { r => List(r) } }else {
      l match {
        case Nil => List.empty
        case head::tail =>
          (combinations(tail, c-1) map { r => head :: r }) ++ combinations(tail, c)
      }
    }
  }

I think this one is good enough to solve this problem (from point of view of interview).

But after solving this I came across a question on SO where folks are trying to solve it without getting in O(n3) complexity.
Kindly suggest me how you would solve it.

Also please suggest me how I should handle this scenario where I think solution I gave is best for the problem.


texts: Exercism: clean and format a phone number in Clojure

texts:
Problem statement

  Phone Number

  Write a program that cleans up user-entered phone numbers so that they can be sent SMS messages.

  The rules are as follows:

  If the phone number is less than 10 digits assume that it is bad number
  If the phone number is 10 digits assume that it is good
  If the phone number is 11 digits and the first number is 1, trim the 1 and use the last 10 digits
  If the phone number is 11 digits and the first number is not 1, then it is a bad number
  If the phone number is more than 11 digits assume that it is a bad number

Proposed Solution

(ns phone-number
  (:require [clojure.string :as str]))

(def non-digits #"\D")
(def parts #"^1?(...)(...)(....)$")
(def error-val ["000" "000" "0000"])

(defn- digits [n] (str/replace n non-digits ""))

(defn- trio-h [n]
  (if-let [ps (re-find parts n)]
    (rest ps)
    error-val))

(defn- trio [n] (-> n digits trio-h))

(defn number [n] (-> n trio str/join))

(defn area-code [n] (-> n trio first))

(defn pretty-print [n]
  (let [[area exch line] (trio n)]
    (format "(%s) %s-%s" area exch line)))

Questions

In pretty-print is the use of let necessary? Or is there a way in Clojure to splice in the result of (trio n) in-place for the call to format? The result of (trio n) is a vector containing three strings and the format call is expecting three %s strings to stick into the format string. If there is an alternative to my use of let, which is preferred?
Are the names ok? Do they read like Clojure names? Is there a convention for naming a one-off helper function?
Is it better to keep trio-h a separate helper function, or let it inside the using function, or would you just use the code in-place instead?
:refering clojure.string/replace triggers a warning (since it collides with clojure.core/replace) so I :refered all of clojure.string. Is there a way to :refer as to avoid the collision?
Do you have other improvements you could suggest?

Tests

See the Exercism page for the Phone Number problem in Clojure


texts: Having less code for the current program

texts:
I am was writing a practice program in javascript and it turned out to work quite alright, however I am not entirely happy with the code. I can't shake the feeling that there is a lot of code which doesn't have to be there, I feel that it can be improved.

The idea of the program is basically, you have a selector, each time you make a choice and hit submit a new set of choices are offered. The choices of the user are stored in an object.

I am interested to know if there is a way to make this code more efficient.

Here is the entire source code (+ the html part)

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Dynamic Selector</title>
</head>
<body>
    <select id="select">
</select>
    <button onclick="updateObject()">Submit</button>
</body>
</html>
<script>
    var select = document.getElementById("select");

    var choice = { time: "", category: "", complexity: "" };
    var time = ["15", "30", "60", "60+"];
    var category = ["knowedge", "experimenting", "self-iprovement", "cooking", "health"];
    var complexity = [1, 2, 3, 4];

    var coef = 0;

    //creates the children for the time choices
    function setChoices() {
        if (coef === 0) {
            for (var i = 0; i < time.length; i++) {
                var node = document.createElement('option');
                node.value = time[i].toString();
                node.innerHTML = time[i];
                select.appendChild(node);
            }
        } else if (coef === 1) {
            for (var i = 0; i < category.length; i++) {
                var node = document.createElement('option');
                node.value = category[i].toString();
                node.innerHTML = category[i];
                select.appendChild(node);
            }
        } else if (coef === 2) {
            for (var i = 0; i < complexity.length; i++) {
                var node = document.createElement('option');
                node.value = complexity[i].toString();
                node.innerHTML = complexity[i];
                select.appendChild(node);
            }
        }
    }

        function updateObject() {
            if (coef === 0) {
                choice.time = select.value;
                console.log(choice.time);
                coef++;
                removeChildren();
                setChoices();
            } else if (coef === 1) {
                choice.category = select.value;
                coef++;
                removeChildren();
                setChoices();
            } else if (coef === 2) {
                choice.complexity === select.value;
                printObject();
                setChoices();
            }
        }

        //removes the children of the "select" element
        function removeChildren() {
            while (select.firstChild) {
                select.removeChild(select.firstChild);
            }
        }

        function printObject() {
            console.log("foobarr");
        }

        removeChildren();
        setChoices();
</script>


texts: Is this a good way to download images from json Api?

texts:
In my SwiftUI app, I'm trying to get some data from a json Api and display this data along with an image. First I have a function that fetches the data from the Api, then I have another function that downloads the image data. The image takes a while to appear(1-2) seconds.
I'm wondering if this is the best way to do it, especially if I'm downloading multiple images to display them in a List or a Grid.
func fetchAPI() {

    URLSession.shared.dataTask(with: url) { (data, response, error) in

/* Code that decodes the json and gets the imageURL string */

            DispatchQueue.main.async {

                self.downloadImage(url: imageURL) // call the function that downloads the imageData
            }
        } catch {
            print("Error: \(error.localizedDescription)")
        }
    }
    .resume()
}

The function that downloads the image:
func downloadImage(url: String) {

    guard let imageURL = URL(string: url) else {
        print("Error: Invalid image URL")
        return
    }

    URLSession.shared.dataTask(with: imageURL) { data, response, error in
        guard let recievedData = data, error == nil  else {
            print("Error: No Data")
            return
        }

        DispatchQueue.main.async {
            self.imageData = recievedData
        }
    }
    .resume()
}


texts:
I've made a method, which inserts a new query parameter, when the value of a select changes, then reloads the page. I've had enough of URL jQuery hax, so I figured it would be a great idea to put the query parameters in an array, and manipulate it that way. I'm a little unsure whether or not this is the best way of doing it, so some input would be appreciated.

HTML

<select id="selCurrency">
   <option value="">Choose currency &hellip;</option>
   <option value="DKK">Danske kroner</option>
   <option value="NOK">Norske kroner</option>
   <option value="SEK">Svenske kronor</option>
</select>

JS

$("#selCurrency").change(function(){
     var val = $(this).val(); // This should be the new CurrencyCode, extracted from a select box
     var pag = window.location.pathname;
     var url = window.location.search;
         url = url.replace("?", "").split("&"); // Clean up the URL, and create an array with each query parameter

     var n = 0;
     for (var count = 0; count < url.length; count++) {
         if (!url[count].indexOf("CurrencyCode")) { // Figure out if if/where the Currency is set in the array, then break out
             n = count;
             break;
         }
     }

     if (n !=0) {
        url.splice(n,1); // If the Currency was set, remove it from the array
     }

     var len = url.length;
     var newUrl = url.join("&"); // Restringify the array

     if (len > 0) { // Check whether or not the currency is the only parameter, then build new URL with ? or &
        newUrl = pag + "?" + newUrl + "&CurrencyCode=" + val;
     } else {
        newUrl = pag + newUrl + "?CurrencyCode=" + val;
     }

     window.location.href = newUrl; // Finished, let's go!
  });

You will notice, that I've used the jQuery selector engine, while the rest is native JS. Would it be smarter/faster to use native JS to check for the onchange event?

document.getElementById("selCurrency").onchange( /* My function right here, mayn */ );


texts: Implementing a Treeview component using React

texts:
Today after watching a getting started course about React, I tried to code my very first React component, a "treeview" as the title says. It does work, but as a newbie I know there are many improvement that can be done.

It receives a data array like the one below:

[{
    descp: 'UNE',
    url: '/tree/une',
    icon: 'icon-list',
    children: [
        {
            descp: 'ATI',
            url: '/tree/une/ati',
            icon: 'icon-layers',
            children: [{
                    descp: 'ATI-VC',
                    url: '/tree/une/ati/ativc',
                    icon: 'icon-pin',
                    children: []
                },
                {
                    descp: 'ATI-CMG',
                    url: '/tree/une/ati/aticmg',
                    icon: 'icon-pin',
                    children: []
                }
            ]
        },
        {
            descp: 'EMGEF',
            url: '/tree/une/emgef',
            icon: 'icon-layers',
            children: []
        },
        {
            descp: 'ECIE',
            url: '/tree/une/ecie',
            icon: 'icon-layers',
            children: []
        },
        {
            descp: 'GEYSEL',
            url: '/tree/une/geysel',
            icon: 'icon-layers',
            children: []
        }
    ]
}]

Maybe the data format can be improve as well but the real deal is the component:

const MyTree = (props) => {
    const { list } = props;
    return (
        list.map((child,i)=>
            <MyTreeNestedItems key={i} data={child} />
        )
    );
};

const MyTreeNestedItems = (props) => {
    const { data } = props;

    const createChildren = (list) => {
        return (
            list.map((child,i)=>
                <MyTreeNestedItems key={i} data={child} />
            )
        )
    }

    let children = null;
    if (data.children.length) {
        children = createChildren(data.children);
    }

    return (

                 {" "}
                { data.descp }

{children}

    );
};

render(<MyTree list={tree} />,document.querySelector('.js-mytree'));

Any tips would be gratefully appreciated.


texts: Making grandchild of root null , the right way in C++

texts:
I am trying to create a multiway tree with the following code in C++. As of now, it is more like a sample piece of code.

I wish to do the following with this piece of code(and I am able to get the desired result):

Create a struct Node of two members : value(of the node) and array of children of the node.
Make 'root's value = 5
Make the children's values equal to 10,20,30 & 40
Make the children of children's values equal to null(=0);

I am getting the desired output , but what I want to know is if I am doing it the right way.

Thanks, in advance.

//multinode tree
#include<iostream>
#define null 0

struct Node
{
    int value;
    Node *child[4];
};

void display(Node *root){
    if(root==null)
        return;
    else{

        std::cout<<root->value<<" ";
        if(root->child[0]!=null)
            for (int i=0;i<4;i++)
            {
                if(root->child[i]!=null)
                    display(root->child[i]);

            }
    }
}

int main()
{
    Node *root=new Node;
    Node *test=null;
    root->value=5;
    int values[]={10,20,30,40};
    int i=0;
    for (i=0;i<4;i++)
    {
        Node *temp=new Node;
        temp->value=values[i];
        root->child[i]=temp;
        for (int j=0;j<4;j++)
        {
            root->child[i]->child[j]=null;
        }
        std::cout<<"Root value "<<root->child[i]->value<<"\n\n ";
    }
    std::cout<<"\n\n\n\n\n";
    display(root);

}


texts: Checking whether any of some large collection of attributes has changed

texts:
I have to check a large number of attributes and do something if any of them have changed. However, right now there are way too many or statements. Is there a better way to do this?

def check_updates
  if self.post_code_changed? || self.preferred_gender_changed?
    # do something
  elsif self.occupation_changed? || self.date_of_birth_changed?
        || self.religion_changed? || self.smoke_changed?
        || self.drink_changed? || self.drugs_changed?
        || self.diet_changed? || self.looking_for_changed?
        || self.edu_status_changed? || self.edu_type_changed?
    # do something else
  end
end


texts:
I have a code that does applies Dijkstra's algorithm for an adjacency list.
The data are taken from a file. In the file, the first line contains the number of vertices and edges, and the remaining lines contain three elements each (the first 2 are the numbers of the vertices and 3rd are the weight of the edges).
The output is written to another file. The main problem is long reading (adding to the list) of elements - 8 seconds versus 2 according to the rules of the correct test. In a file for reading, there are 400,000 such lines. How can I speed up the reading?
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <list>
#include <vector>
#include <queue>
using namespace std;
# define INF 0x3f3f3f3f
typedef pair<int, int> iPair;

class Graph
{
    int V;
    list< pair<int, int> >* adj;
public:
    Graph(int V);
    void addEdge(int u, int v, int w);
    void shortestPath(int s);
};

Graph::Graph(int V)
{
    this->V = V;
    adj = new list<iPair>[V];
}

void Graph::addEdge(int u, int v, int w)
{
    adj[u].push_back(make_pair(v, w));
    adj[v].push_back(make_pair(u, w));
}

void Graph::shortestPath(int src)
{
    priority_queue< iPair, vector <iPair>, greater<iPair> > pq;
    vector<int> dist(V, INF);
    pq.push(make_pair(0, src));
    dist[src] = 0;
    while (!pq.empty())
    {
        int u = pq.top().second;
        pq.pop();
        list< pair<int, int> >::iterator i;
        for (i = adj[u].begin(); i != adj[u].end(); ++i)
        {
            int v = (*i).first;
            int weight = (*i).second;
            if (dist[v] > dist[u] + weight)
            {
                dist[v] = dist[u] + weight;
                pq.push(make_pair(dist[v], v));
            }
        }
    }
    ofstream file1("C:\\Tests\\123.txt");
    for (int i = 0; i < V; ++i)
        cout << dist[i] << " ";
    file1.close();
}

int main()
{
    ifstream file("C:\\Tests\\21");
    int number_of_veretexes, edges;
    file >> number_of_veretexes >> edges;
    Graph g(number_of_veretexes);
    int _first_, _second_, _third_;
    for (int i = 0; i < edges; i++) {
        file >> _first_ >> _second_ >> _third_;
        g.addEdge( _first_ - 1, _second_ - 1, _third_);
    }
    g.shortestPath(0);
    file.close();
}


texts:
I'd like to check my understanding and usage of the AutoMapper in my ASP.Net MVC app.

I setup the maps in Application_Start:

 Mapper.CreateMap<Customer, CustomerViewModel>();
 Mapper.CreateMap<CustomerViewModel, Customer>();
 Mapper.AssertConfigurationIsValid();

To return a list of users associated with the logged in user, in my Customer Controller I have:

    //
    // GET: /Customer/

    public ActionResult Index()
    {
        var customer = db.Customers.Where(x => x.UserName == User.Identity.Name).ToList();
        IList<CustomerViewModel> customerVM = Mapper.Map<IList<Customer>, IList<CustomerViewModel>>(customer);
        return View(customerVM);
    }

To Edit a specific customers details I am using:

    //
    // GET: /Customer/EditPartial
    public ActionResult EditPartial(int id)
    {
        var customer = db.Customers.Where(x => x.UserName == User.Identity.Name && x.CustomerId == id).FirstOrDefault();
        CustomerViewModel customerVM = Mapper.Map<Customer, CustomerViewModel>(customer);
        return PartialView(customerVM);
    }

Where I Post back updates after making changes in the EditPartial view:

    //
    // POST: /Customer/EditPartial
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult EditPartial(CustomerViewModel customerVM)
    {
        if (ModelState.IsValid)
        {
            Customer customer = db.Customers.Where(x => x.UserName == User.Identity.Name && x.CustomerId == customerVM.CustomerId).FirstOrDefault();
            if (customer == null)
            {
                return HttpNotFound();
            }
            customer.CustomerName = customerVM.CustomerName;

            // How do I use AutoMapper here, instead of updating the domain model directly
            customer.Email = customerVM.Email;
            db.Entry(customer).State = EntityState.Modified;
            db.SaveChanges();
            /////////////////

            // Now I want to return a customer list again
            // Is this the best way to do it again
            var customer2 = db.Customers.Where(x => x.UserName == User.Identity.Name).ToList();
            IList<CustomerViewModel> customerVM2 = Mapper.Map<IList<Customer>, IList<CustomerViewModel>>(customer2);

            return PartialView("CustomerListPartial", customerVM2);
        }
        this.Response.StatusCode = 400;
        return PartialView("EditPartial", customerVM);
    }

The code above works, I'm just not sure about using AutoMapper in the Post, and if my way of returning a partial list of customers is the best method.


texts: Flexible generic event system that binds to objects

texts:
I have been trying to create an event queue system using SDL. I've been trying to use this for Pong. The game is not even finished yet, but I stopped work to examine how my event system is organized.

Event_Queue - This is the heart of the system. All events go through here and all listeners come through here.
Event - This holds a name string, a type string, and a Boost.Any object to be able to package any type of data along with it. Boost.Any will act as a wrapper for another general data structure, but in the case that it isn't general enough, another can be easily adopted.
Event_Receivable - Interface between Event_Receiver and object; I think it's unclean but I don't know of a better way than inheritance to do this.
Event_Receiver - The object that is tacked onto an object to be able to receive objects. It is also a type of interface--logic will be handled within the object, preferably through a Logic module, and is intended to be hooked up to a scripting API later.
Event_Sender - This is supposed to send events onto the Event_Queue. This will probably be improved so that I can just use std::move or something, but this is supposed to always be the outlet from where Events are fired.

Does this constitute a complete event system? Are there any flaws besides the glaring ignorance regarding copy, references, and move?

Event_Queue.h:

class Event_Queue
{
private:

    SDL_Event input;

    std::queue<Event> event_queue;
    std::vector<Event_Receiver*> receiver_list;
public:
    void add_receiver(Event_Receiver* receiver_ptr);
    bool remove_receiver(Event_Receiver* receiver_ptr);

    void push_event(Event e);

    void poll_input();
    void poll_event();

};

Event_Receivable.h:

class Event_Receivable
{
public:
    virtual ~Event_Receivable() = 0;
    virtual void on_notify(Event* e) = 0;

};

Event_Receiver.h:

class Event_Receiver
{
public:
    Event_Receiver(Event_Receivable* owner_obj);
    ~Event_Receiver();

    void receive_event(Event* e);
    void notify_owner(Event* e);
    void set_owner(Event_Receivable* owner_obj) {owner = owner_obj;}

    Event_Receivable* get_owner_obj() {return owner;}

private:
    Event_Receivable* owner;

};

Event.h:

#include "Common.h"
#include "boost/any.hpp"

/*
 * Event is used extensively within the program.
 * It is the basis for all messages in the event system.
 * Objects will send and receive events.
 *
 * It uses boost::any in order to be able to
 * attach any kind of data to be read.
 *
 * Event is meant to be extremely flexible in order to
 * be extensible to many different types of games.
 */
class Event

    {
    private:
        std::string name;
        std::string type;
        std::vector<boost::any> info;
    public:
        Event(std::string name_str, std::string type_str)
        {
            name = name_str;
            type = type_str;
        }

        void set_name(std::string str) {name = str;}
        void set_type(std::string str) {type = str;}
        void attach_data(boost::any data) {info.push_back(data);}

        std::string get_name() {return name;}
        std::string get_type() {return type;}
        boost::any get_info() {return info;}
    };

Event_Sender.h:

class Event_Sender
{
public:
    void send_event(Event e);
    void send_event(Event e, Event_Queue q);

    void set_event_queue(Event_Queue e_queue) {event_queue = &e_queue;}

    Event_Queue* get_event_queue() {return event_queue;}

private:
    Event_Queue* event_queue;
};

GitHub

This code already does compile correctly with dependencies sorted out, but I need feedback on the system.


texts: Extracting First, Last & Middle Name from a full name

texts:
My function takes a string of Name and returns First Name, Last Name and Middle Name as output.

Please review and help me optimize it.

    //input --> Hamza Khan
    ProcessFullName(full_name): Object {
        var Obj = {
            FirstName: "",
            LastName: "",
            MiddleName: ""
        };
        var splitName = full_name.split(" ");
        if (splitName.length>0) {
            switch (splitName.length) {
                case 1:
                    Obj.FirstName = splitName[0];
                    break;
                case 2:
                    Obj.FirstName = splitName[0];
                    Obj.LastName = splitName[1];
                    break;
                case 3:
                    Obj.FirstName = splitName[0];
                    Obj.MiddleName = splitName[1];
                    Obj.LastName = splitName[2];
                    break;
            }
        }
        return Obj;
    } //Output --> { FirstName: "Hamza", LastName: "Khan", MiddleName: "" }


texts:
I need to remove last text after : in my String and : too. I have tried this. Please review. If there is a better way to do, please tell me.

String test = "temp:content:region:deposit:up";
System.out.println(test.replace(test.substring(test.lastIndexOf(":"), test.length()), ""));


texts:
I am working on a custom Bootstrap 3 carousel, with vertical, unidirectional, slide transitions.

I want to prevent slide transitions from overlapping when the bullets are clicked in random order and rapid succession.

I came up with this solution that relies on disabling them as long as a slide transition is in progress, then enabling them between transitions:

var carouselDuration = function() {
  $.fn.carousel.Constructor.TRANSITION_DURATION = 1000;
}

carouselDuration();
// While a transition is in progress (slide event), do this
$('#myCarousel').on('slide.bs.carousel', function (e) {
    var $indicator = $(this).find('.carousel-indicators>li');
    $indicator.css('pointer-events', 'none');
});

// While a transition has finished (slid event), do this
$('#myCarousel').on('slid.bs.carousel', function (e) {
    var $indicator = $(this).find('.carousel-indicators>li');
    $indicator.css('pointer-events', 'auto');
});
.carousel.vertical {
  position: relative;
}

.carousel.vertical .carousel-inner {
  height: 100%;
  width: auto;
}

.carousel.vertical .carousel-inner>.item {
  width: auto;
  transition: 1s ease-in-out;
  transform: translate3d(0, 100%, 0);
  top: 0;
}

.carousel.vertical .carousel-inner>.next,
.carousel.vertical .carousel-inner>.prev,
.carousel.vertical .carousel-inner>.right {
  transform: translate3d(0, 100%, 0);
  top: 0;
}

.carousel.vertical .carousel-inner>.left,
.carousel.vertical .carousel-inner>.prev.right,
.carousel.vertical .carousel-inner>.next.left,
.carousel.vertical .carousel-inner>.active {
  transform: translate3d(0, 0, 0);
  top: 0;
}

.carousel.vertical .carousel-inner>.active.right,
.carousel.vertical .carousel-inner>.active.left {
  transform: translate3d(0, -100%, 0);
  top: 0;
}

.carousel.vertical .carousel-indicators {
  display: inline-block;
  width: auto;
  padding: 0;
  margin: 0;
  left: auto;
  right: 10px;
  bottom: 2px;
  z-index: 9;
  font-size: 0;
}

.carousel.vertical .carousel-indicators li {
  border: none;
  cursor: pointer;
  display: inline-block;
  width: 18px;
  height: 18px;
  text-indent: -9999px;
  background: url("https://grgs.ro/1/i/sprite.png") no-repeat -528px -502px;
}

.carousel.vertical .carousel-indicators li.active {
  background-position: -528px -524px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Still, I am looking for a queuing mechanism, as it is more natural and elegant.


texts:
/((([\w -]+)|("[\w -]+"))( *, *)?)+/

http://refiddle.com/18ql

I'm trying to use a PHP regex to sanitize a user input for a list of fonts. The above one seems to work nicely, but also feels a bit long and redundant, having two [\w -]*s, and allowing a trailing comma, and possibly stuff I can't see. Can this be more efficient (smaller, less redundant, more secure)?

Examples

The regex should match these:

Roboto
"Roboto"
"Roboto Condensed"
Roboto Condensed
Roboto Condensed, Roboto
"Roboto Condensed", Roboto
Roboto Condensed, "Roboto"
"Roboto Condensed", "Roboto", sans-serif

or any string that matches the W3C specification for a CSS font-family property

It must be able to match these, but not any preceding (e.g. /*) or succeeding (e.g. ; DROP TABLE foo) string that might cause errors and open up exploits. So, it should match the font-family list (bold) in the following example, but not the surrounding potentially malicious characters.

  /*"Roboto Slab", "Helvetica Neue", "Arial", sans-serif; DROP TABLE foo --

Similarly, I want it to also remove strings that someone might not know would produce broken code:

  font-family:"Roboto Slab", "Helvetica Neue", "Arial", sans-serif; /* My fonts */

My input-handling function:

$userFontName = sanitizeFontName($_GET['font'])

function sanitizeFontName($fontName)
{
    $match = null;
    preg_match('/((([\w -]+)|("[\w -]+"))( *, *)?)+/', $fontName, $match); // Only get a W3C font list. Proven here: http://refiddle.com/18ql
    return $match[0]; // only one
}

Demo


texts: Iterating over symmetric matrix in python


texts: Count values in one dataframe that are less than all the values in another

texts:
I currently have 2 dataframes, A and B. These dataframes are generated in runtime, and increase in size according to parameters in the program execution.

I need to evaluate how many times a value in dataframe A is lesser than all the values in dataframe B.

For example:

Dataframe A
+-----+-------+
| id  | value |
+-----+-------+
|   1 | 0.23  |
|   2 | 1.2   |
+-----+-------+
Dataframe B
+-----+-------+
| id  | value |
+-----+-------+
|   1 | 0.22  |
|   2 | 1.25  |
|   3 | 0.3   |
|   4 | 0.5   |
|   5 | 0.9   |
|   6 | 0.0   |
+-----+-------+

I need to check how many values greater than 0.23 (for example) are in dataframe B. in this case 4 of the 6.

My first try with this was using this code. In this case, bio_dataframe is dataframe A, an random_seq_df is dataframe B.

for bio_row in bio_dataframe.itertuples():
    total = 0
    for ran_row in random_seq_df.itertuples():
        if bio_row[2] < ran_row[2]:
            total += 1

As you can see, i use itertuples for fast iteration of the rows of the dataframes.
This approach works "well" for dataframes below 25000 rows, but beyond that it starts to get painfully slow.

So my next approach was this.

  final_res is a column in the dataframe.

for bio_row in bio_dataframe.itertuples():
    a = bio_row[2]
    total = random_dataframe.eval('final_res > @a')

It works excellent until 100000 rows, beyond that the story repeats.

I'm hitting a wall here and I've run out of ideas to test. Is there any way to improve the code? Am I missing something, or some snippet to make it faster?


texts:
Techies--
This routine does more once the channels + the subsets of existing batch arrays are re-distributed for processing. However, the success of that will only work as well as the initial splits. The threshold value is dubbed here, but it will come from app.config as configurable setting. Obviously the jagged string array is dubbed for review purposes. The real values will be coming from another routine and will frequently have counts > 100000. The 3 lines of comments where one will do is a product of formatting the code for StackExchange.

Please review what's here.

   #region Channel Assignment Testing

    static void ChannelAssign()
    {
        int THRESHOLD = 1;

        string[] batch = new string[]
            { "item1", "item2", "item3", "item4","item5","item6","item7" };
        int batchcnt = batch.Count();
        int subsetqty; // subset batch item quantity
        string[][] subsets; // Split extension returns these values
        int channelidx; // index for channels back from Split

        if (THRESHOLD != 0) //avoid accidental division by 0.
        {
            float channels = batchcnt/THRESHOLD;
            if (channels < 1) // can handle all items in existing batch based on
                              // threshold setting.
            {
                channels = 1; // dub as a single channel
                subsetqty = batchcnt; // process all batch items in batch
                channelidx = 1; // dub index for a single channel
                subsets = batch.Split(batchcnt); // ship the batchcount
                                                 // to split routine.
            }
            else // we need at least 2 channels; round up from float
                 // and decide how many.
            {
              channels =  (int)Math.Round(channels,
                            MidpointRounding.ToEven); //determines channel# estimate
              subsetqty = batchcnt/(int)channels; // estimates # of
                                                  // existing batch items to
                                                  // place in each subset
              subsets = batch.Split(subsetqty); // actual subsets of batches returned
              channelidx = subsets.GetLength(0); //gets actual channel# assigned
                                                 // by split

            }

            //distribute contents of batch into subsets for channel consumption
            for (int channel = 0; channel < channelidx; channel++)
            {
                for(int i = 0; i < subsets[channel].Length; i++)
                {
                    Console.WriteLine(" Channel:" + channel.ToString() + " ItemName:
                      {0} ", subsets[channel][i]);
                }
            }
        }
        else
        {
            Console.WriteLine("Threshold value set to zero. This is an
                                invalid value. Please set THRESHOLD.");
        }

    }

    #endregion

Split Extension

        public static T[][] Split<T>(this T[] arrayIn, int length)
        {
            bool even = arrayIn.Length % length == 0;
            int totalLength = arrayIn.Length / length;
            if (!even)
                totalLength++;

            T[][] newArray = new T[totalLength][];
            for (int i = 0; i < totalLength; ++i)
            {
                int allocLength = length;
                if (!even && i == totalLength - 1)
                    allocLength = arrayIn.Length % length;

                newArray[i] = new T[allocLength];
                Array.Copy(arrayIn, i * length, newArray[i], 0, allocLength);

            }

            return newArray;
        }


texts: Calculating Earnings from attendance details

texts:
In a C# win forms payroll application I need to calculate employee salary based on their attendance. I've written a stored procedure which calculates earnings of all employees from the data available in attendance table. So when the application calls the SP the data will be shown on a data grid view and then immediately these data will be saved in SalaryTrans table.

Please note in following demo code I've excluded the use of Interfaces and DI.

Since this is an object oriented development employing MVP design pattern, could you please advice me whether the way I've done this acceptable?

I know that I've not used a Model, in this case SalaryModel as the DataService return a DataSet object with all earnings figures of all employees. So Could you please show me a way  of using a Model (in this case SalaryModel) in this scenario if possible?

Form

public partial class frmSalary : Form
{
    public frmSalary()
    {
        InitializeComponent();
    }

    private void btnProcessEarning_Click(object sender, EventArgs e)
    {
        SalaryPresenter presenter= new SalaryPresenter();
        presenter.ShowEarnings();
        presenter.SaveEarnings();
    }
}

Presenter

class SalaryPresenter
{
    private void ShowEarnings()
    {
        _View.dgEmployeeSalary.DataSource = CalculateEarnings(dtpStartDate.Value,dtpEndDate.Value);
    }

    private void SaveEarnings()
    {
        _DataService.InsertEarnings(dgEmployeeSalary);
    }

    private DataTable CalculateEarnings(DateTime startDate, DateTime endDate)
    {
        return _DataService.Calculate(startDate, endDate);
    }
}

Data Service

class DataService
{
    public DataTable Calculate( DateTime fromDate, DateTime toDate)
    {
        using (SqlConnection sqlConnection = new SqlConnection(db.GetConnectionString))
        {
            using (SqlCommand sqlCommand = new SqlCommand("dbo.sp_Earnings", sqlConnection))
            {
                sqlCommand.CommandType = CommandType.StoredProcedure;
                sqlCommand.Parameters.Add("@fromDate", SqlDbType.DateTime).Value = fromDate;
                sqlCommand.Parameters.Add("@toDate", SqlDbType.DateTime).Value = toDate;
                using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCommand))
                {
                    using (DataSet dataSet = new DataSet())
                    using (DataTable dataTable = new DataTable())
                    {
                        sqlConnection.Open();
                        dataSet.Tables.Add(dataTable);
                        sqlAdapter.Fill(dataTable);
                        return dataTable;
                    }
                }
            }
        }
    }

    public void InsertEarnings(DataGrid dataGrid)
    {
        using (SqlConnection newCon = new SqlConnection(db.GetConnectionString))
        {
            foreach (DataGridViewRow row in dataGrid.Rows)
            {
                if (row.Cells[1].Value != null)
                {
                    string commandString = "IF NOT EXISTS (SELECT * FROM SalaryTrans WHERE emp_id=@emp_id) BEGIN INSERT INTO salaryTrans..."
                    //Database transaction code here
                }
            }
        }
    }
}


texts: Check if 2 rectangles fit in another one, given their length and height

texts:
I was very intrigued with the manner to solve this problem. The program needs to know if 2 rectangles fit in another one, considering the lines of the 2 rectangles are always parallel to the other one's.

I know I could just put everything in a single if, but is that more readable? I want to know a good approach for this situation, using only conditions.

NOTE: x and y represent the first rectangle's width and height (the one that will fit the other 2) and l1, h1, l2, and h2 represent the other 2 rectangles' width and height.

#include <stdio.h>

int main(void)
{
    int x, y, l1, h1, l2, h2;

    scanf("%d %d %d %d %d %d", &x, &y, &l1, &h1, &l2, &h2);

    if ((l1 + l2 <= x && h1 <= y && h2 <= y) ||
    (h1 + h2 <= x && l1 <= y && l2 <= y))
    {
        puts("They fit.");
    }
    else if ((l1 <= x && h2 <= x && h1 + l2 <= y) ||
    (h1 <= x && l2 <= x && l1 + h2 <= y))
    {
        puts("They fit.");
    }
    else if ((l1 <= y && h2 <= y && h1 + l2 <= x) ||
    (h1 <= y && l2 <= y && l1 + h2 <= x))
    {
        puts("They fit.");
    }
    else if ((l1 + l2 <= y && h1 <= x && h2 <= x) ||
    (h1 + h2 <= y && l1 <= x && l2 <= x))
    {
        puts("They fit.");
    }
    else
    {
        puts("They don't fit.");
    }
    return 0;
}


texts: Hiding all list items except the current and next element

texts:
Only current and next element (cNum) is to be shown; in case it is the last element in the structure - the first element should be shown.

var childNum = $('#h').roundabout("getChildInFocus");
var cNum = (Number(childNum)) + 2;
if (cNum == 5) cNum = 1;

$("#h li").hide();
$("#h li:nth-child(" + cNum + ")").show();

if (cNum == 4) {
    $("#h li:nth-child(1)").show();
} else {
    $("#h li:nth-child(" + (Number(cNum) + 1).toString() + ")").show();
}