Keyboard Printing with Teensy I'm trying to write a piece of code that will mimic ASCII keyboard output. It uses the keyboard library from pjrc, but the application I'm working on requires outputting string sequences rather than individual keys (the C++ interface exposes Keyboard.print, which does exactly what I want, except that I'm trying to stick to C for learning purposes).

Here's a kick at it;

[snip]
#include <string.h>
#include "usb_keyboard.h" // definitions for the /KEY_\w+/ symbols

int key_from_char(char c){
  if (c >= 'a' && c <= 'z') return c + KEY_A - 'a';
  if (c >= 'A' && c <= 'Z') return c + KEY_A - 'A';
  if (c >= '1' && c <= '9') return c + KEY_A - '1';
  if (c == '0') return 39; // 0 is low in ASCII, high in the USB key definition

  // there's no easy mapping between the other ASCII characters and
  // USB keyboard keys, so these are all manually represented
  switch (c) {
  case ' ': return KEY_SPACE; break;
  case '!': return KEY_1; break;
  case '"': return KEY_QUOTE; break;
  case '#': return KEY_NUMBER; break;
  case '$': return KEY_4; break;
  case '%': return KEY_5; break;
  case '&': return KEY_7; break;
  case '\'': return KEY_QUOTE; break;
  case '(': return KEY_9; break;
  case ')': return KEY_0; break;
  case '*': return KEYPAD_ASTERIX; break;
  case '+': return KEYPAD_PLUS; break;
  case ',': return KEY_COMMA; break;
  case '-': return KEYPAD_MINUS; break;
  case '.': return KEY_PERIOD; break;
  case '/': return KEYPAD_SLASH; break;

  case ':': return KEY_SEMICOLON; break;
  case ';': return KEY_SEMICOLON; break;
  case '<': return KEY_COMMA; break;
  case '=': return KEY_EQUAL; break;
  case '>': return KEY_PERIOD; break;
  case '?': return KEY_SLASH; break;
  case '@': return KEY_2; break;

  case '[': return KEY_LEFT_BRACE; break;
  case '\\': return KEY_BACKSLASH; break;
  case ']': return KEY_RIGHT_BRACE; break;
  case '^': return KEY_6; break;
  case '_': return KEY_MINUS; break;
  case '`': return KEY_TILDE; break;

  case '{': return KEY_LEFT_BRACE; break;
  case '|': return KEY_BACKSLASH; break;
  case '}': return KEY_RIGHT_BRACE; break;
  case '~': return KEY_TILDE; break;

  default: return 0;
  }
}

int modifier_from_char(char c){
  if ((c >= 'A' && c <= 'Z') ||
      // not sure how useful it is to put chars instead of ints for the rest of these
      c == '!' || c == '"' ||
      (c >= '$' && c <= '&') ||
      c == '(' || c == ')' ||
      c == ':' || c == '<' ||
      (c >= '>' && c <= '@') ||
      c == '^' || c == '_' ||
      (c >= '{' && c <= '~')) return KEY_SHIFT;

  return 0;
}

int8_t usb_keyboard_print(char *s){
  int s_len = strlen(s);
  int i;

  for(i = 0; i < s_len; i++){
    usb_keyboard_press(key_from_char(s[i]), modifier_from_char(s[i]));
  }
}

It seems to work, when I do

int main(void) {
   ...
   usb_keyboard_print("abcdABCD1234!@#$%^&*()_+|~{}:\">?<-=\\`[];',./");
   ...
}

the character sequence

abcdABCD1234!@\$%^&*()_+|~{}:">?<-=\`[];',./

is output as if by keyboard.

All comments welcome, but I also have specific points/questions

It seems like there should be an easier way to do this. I mention above that the C++ version of the usb_keyboard library provides a Keyboard.print which does essentially the same thing, but I haven't found anything similar for plain C.
Are there any issues I'm missing about USB key codes that would make this code wonk out based on nationality settings? How would you go about internationalizing it?
This is basically the first C code I've written since getting out of high-school, so please point out style errors and inefficiencies with extreme prejudice.

Don't subtract absolute values:

    if (c >= 'a' && c <= 'z') return c - 93;

It makes it hard to understand what you are doing when you subtract integer literals from character codes. I would normally expect some form of value that conveys some meaning. For example lets assume ASCII (You probably want your keyboard thing but I don't know the appropriate macro).

 if (c >= 'a' && c <= 'z') return c + 3 - 'a';  // For some reason you want 'a' to map to 3
                                                // If we assume ASCII 'a' => 96

 if (c >= 'A' && c <= 'Z') return c + 4 - 'A';  // For some reason you want 'A' to map to 4
                                                // If we assume ASCII 'A' => 65

Either you have some other requirement that is not ASCII (very possible), you want 'a'/'A' to map to some non zero number or you have a bug. But it is hard to tell with the way you have written your code as the literal values 93 and 61 have no real meaning.


Golang matrix package I developed a small package to do matrix math. I just learned Go so I may have done it wrong.

package matrix

import "fmt"
import "errors"
import "math"

type Matrix [][]float64

func Print(m Matrix) {
    fmt.Println(m)
}

func Zeros(rows, cols int) Matrix {
    m := make([][]float64, rows)
    for i := 0; i < rows; i++ {
        m[i] = make([]float64, cols)
    }
    return m
}

func Map(f func(float64) float64, m Matrix) Matrix {
    mapped := Zeros(len(m), len(m[0]))
    for i, row := range m {
        for j, val := range row {
            mapped[i][j] = f(val)
        }
    }
    return mapped
}

func Norm(m Matrix) float64 {
    var norm float64
    for _, row := range m {
        for _, val := range row {
            norm += math.Abs(val)
        }
    }
    return norm
}

func Transpose(m Matrix) Matrix {
    transposed := Zeros(len(m[0]), len(m))
    for i, row := range m {
        for j, val := range row {
            transposed[j][i] = val
        }
    }
    return transposed
}

func Multiply(a, b Matrix) (Matrix, error) {
    if len(a[0]) != len(b) {
        return nil, errors.New("Multiplication is not defined")
    }
    m := Zeros(len(a), len(b[0]))
    for i := 0; i < len(a); i++ {
        for j := 0; j < len(b[0]); j++ {
            for k := 0; k < len(b); k++ {
                m[i][j] += a[i][k] * b[k][j]
            }
        }
    }
    return m, nil
}

And here is a code using the package:

package main

import "matrix"

func main() {
    m := matrix.Map(func (f float64) float64 {
        return 1
    }, matrix.Zeros(2, 2))
    prod, _ := matrix.Multiply(m, m)
    println(matrix.Norm(prod))
}

In your code you often use the expressions len(m) and len(m[0]). The code would become clearer if you defined proper names for these expressions, like:

func (m Matrix) Rows() int { return len(m) }
func (m Matrix) Cols() int { return len(m[0]) }

This way, you can write zeros := matrix.Zeros(m.Rows(), m.Cols()), which make the code operate in mathematical terms instead of those of the implementing programming language. These additional methods won't affect the performance of your program since the compiler will generate equally efficient code for these method calls. You can verify this by looking at the generated assembly code using go tool objdump. And if there should really be a difference, file a bug report at https://github.com/golang/go/issues.

To see whether you defined a good API for your matrix package, you should write a corresponding unit test:

package matrix_test

import "testing"

func TestZeros(t *testing.T) {
    m := matrix.Zeros(3, 3)
    ...
}

Note that I wrote package matrix_test instead of the usual package matrix. This little change (which is also little-known) makes this test file a black-box test, which can only access the exported things from the matrix package.

At this point I thought that there were no way to access an individual element of the matrix. Therefore you should add another method:

func (m Matrix) At(row, col int) float64 { return m[row][col] }

Maybe it is possible to access the matrix elements using the [] operator, but I would not recommend this since you might want to implement the matrix later in a different way. Maybe you will mainly handle sparse matrices, where most of the elements are zero. Then you would need to change the implementation type to be more memory-efficient, and that change should not affect any code that already uses your package.

Another benefit of the At method is that it clearly defines that the ordering of the coordinates is row, col. I don't know whether mathematicians are always consistent about this little detail, so it's better to explicitly document it somewhere. Programmers definitely aren't consistent in this regard, not even after 60 years of confusion. There's (x, y), (top, left), (left, top), (height, width), (row, col), (col, row), and so on.


Kalaha Solver: finding the marbles As with my other question this is regarding my Kalaha solver.

Currently the way I find out the optimal progression of moves is with a command like this:

snd $ head $ reverse $ sortByMostInStore $ pickAllPaths $ generatePotList 4

The snd is there to just get the list of moves from the ([Pot], [Int]) pair and the reverse is there because the sorting is ascending. My main problem is that pickAllPaths is really taking every possible path. This results in manageable execution time for generatePotList 5 with 17352 paths, but bring it up to 6 marbles in each pot and that results in 7657399 paths, which takes a significantly longer time to compute.

-- The [Int] is the list of starting positions you picked up marbles from.
pickAllPaths :: [Pot] -> [([Pot], [Int])]
pickAllPaths startingListOfPots = resultingPotsAndPaths where
    resultingPotsAndPaths = branchLoop startingListOfPots []

    branchLoop :: [Pot] -> [Int] -> [([Pot], [Int])]
    branchLoop listOfPots pathTaken
        | null validStartingPositions = [(listOfPots, pathTaken)]
        | otherwise = loopHelper validStartingPositions listOfPots pathTaken []
        where
            validStartingPositions = map position $ filter (not . isPotEmpty) potsOwnedByPlayer
            potsOwnedByPlayer = take 6 listOfPots

    loopHelper :: [Int] -> [Pot] -> [Int] -> [([Pot], [Int])] -> [([Pot], [Int])]
    loopHelper [] _ _ returnList = returnList
    loopHelper (x:xs) listOfPots pathTaken returnList
        | not $ landsInStore = loopHelper xs listOfPots pathTaken combinedList
        | otherwise = branchLoop resultingPots (pathTaken ++ [x]) ++ loopHelper xs listOfPots pathTaken returnList
        where
            (resultingPots, landsInStore) = makeStartingMove listOfPots x
            combinedList = ((resultingPots, (pathTaken ++ [x])) : returnList)

Since I'll generally only be interested in the three best (and maybe worst) paths, which is less than 1% of all the calculated paths, I'm sure there must be a better way of doing this.

Is there a way to avoid unnecessary recursion?

The standard trick is to skip portions of the search space that cannot bring a better solution than the ones found so far. For this you need to:

Remember the best solution found so far (or several best solutions, if you want).
Estimate an upper bound on possible scores that can be achieved from a given game state.

Then, given a partial game state, you compare the estimated upper bound to the current best solution, and if it's lower, there is no need to process the game state. The better the estimate, the more unnecessary processing is skipped.

Depending on the game it's might or it might not be possible to make a precise estimate. If it's not possible, you can use approximate examples. But there is a trade-off: The less precise estimate the higher chance you'll miss the best solution (but most likely the returned solution would be good enough).


Correct usage of EF's DBContext in ASP.NET MVC application with Castle Windsor I am trying to use Entity Framework as simple as posible. Use UnitOfWork and Repository patterns seems to be overkill because whole web application will be pretty straightforward. I came with this idea:

public class Entity
{
    ...
}

public class MyContext : DbContext
{
    //Set database connection details here.

    public DbSet<Entity> Entities{ get; set; }
}

Register DBContext with my implementation:

public class PersistenceInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Component.For<DbContext>()
                                    .ImplementedBy<MyContext>()
                                    .LifestylePerWebRequest()
                          );
    }
}

And finally I am using DBContext in controller this way:

public class HomeController : Controller
{
    private DbContext db;

    public HomeController(DbContext db)
    {
        this.db = db;
    }

    public ActionResult Index()
    {
        var entity = new Entity
        {
            //Set properties here.
        };

        db.Set<Entity>().Add(entity);
        db.SaveChanges();

        return View();
    }
}

Is this correct approach? Could there be any memory leaks or potential DBContext lifetime management problems? Could there be any problem with too many database connections opened?

I would say that this could be correct. From my quick testing it looks like it is working even when I need to use DBContext in component which is then used in controller. So DBContext instance will be shared for everything per one request. Which is the way how it should be used, I guess.

You're doing it right - per-request lifestyle is exactly what you need, and you got it; this ensures your favorite IoC container disposes your context at the end of each request, and serves a new instance at each new one.

One thing bothers me though, and it's not about your code:

  Use UnitOfWork and Repository patterns seems to be overkill because whole web application will be pretty straightforward.

You're using Entity Framework. DbContext, with its DbSet<T>'s, is a unit-of-work/repository pattern implementation. Some will argue it's done wrong and it's their right to be religious about a design pattern. The point is that if you use it correctly, a DbContext is a perfectly acceptable unit of work, especially if you're looking to get the damn thing done and in-line with KISS. Just make sure you call SaveChanges() as little as possible - once per request, i.e. once per instance.

If you're worried about db connections, open up your favorite SQL profiler against your database server instance, and see for yourself!

Bottomline, a DbContext is an abstraction layer over lots, lots of plumbing already. Abstracting it is often over-the-top, unless you wish to decouple your data layer from the rest of your app (say, swap EF for NHibernate).


Random date gen class. Returns a tuple of a start date and end date Just interested in any comments about the way the code is written. I am very new to python and programming. I did think about a func with a generator, but thought this approach was better.

from datetime import date
from datetime import timedelta

import calendar
import random

class rand_dates(object):
    '''
        returns a date range as tuple of a random start date in the current year and an end date + random.randint(term) param.
    the end date can exceed the current year.
        my usage: i want a random reservation date for a hotel stay.
    A base year can also be passed as a param if another year is required other than the current year
    '''

    def __init__(self, term = 5, year=None):
        self.term = term
        self.year = year

    def __iter__(self):
        return self

    def next(self):
        td = date.today()
        if self.year == None:
            y = td.year
        else:
            y = self.year

        m = random.randint(1,12)
        d_in_month = calendar.monthrange(y,m)[1]
        d = random.randint(1,d_in_month)
        sd = date(y,m,d)
        ed= sd + timedelta(days=random.randint(1,self.term))
        return (sd,ed)

You thought about using a generator… and why did you reject the idea?  If you have an object that does nothing other than iterating, then you might as well make it a generator — that's exactly what they are for.

The code is generally sound.  In my opinion, it could flow better if you defined the variables in a more logical order: (random year, random month, random day), followed by (random span), then packaging the results.

The meaning of the term parameter is unclear.  I would prefer a more explicit name.  The default value, 5, is unexpected to me.  Choose either:

A "sensible" default of 1 day, because that is a natural lower limit for a hotel stay (unless you run one of those sleazy hotels that rents rooms by the hour)
A default value of 0 days, because 0 is the additive identity
No default at all: make it a required parameter

In any case, it's probably a good idea to handle max_days=0 correctly without crashing.

The docstring is a bit cumbersome, and slightly self-contradictory when it comes to explaining the year parameter.

import calendar
from datetime import date, timedelta
import random

def rand_dates(max_days=1, year=None):
    '''
    Returns a date range as (start_date, end_date) tuple.

    The start date is a random date in the specified year (defaulting
    to the current year).

    The end date is a random date between 1 and max_days (inclusive) after
    the start date.

    Example usage: Picking random check-in and check-out dates for a hotel stay.
    '''
    while True:
        y = year or date.today().year
        m = random.randint(1, 12)
        d = random.randint(1, calendar.monthrange(y, m)[1])
        days = random.randint(1, max_days) if max_days > 0 else 0
        start_date = date(y, m, d)
        yield start_date, start_date + timedelta(days=days)


Inserting a name into a database table I want to ask you if my PHP code is safe enough. I don't know if I should escape special characters in string after regex validation:

<?php

require_once '../../../wp-load.php';

$errors = [];

if (preg_match('/[^a-ząćęółśżźń ]/i', $_POST['name']) || strlen(trim($_POST['name'])) == 0 || strlen($_POST['name']) > 60) {
    $errors[] = "Invalid name";
}

if (empty($errors)) {
    echo json_encode(['status' => true]);
    $wpdb->query($wpdb->prepare("INSERT INTO people VALUES(null, %s)", $_POST['name']));
} else {
    echo json_encode(['status' => false, 'errors' => $errors]);
}

And what if i use PDO prepare instead of wordpress function?

In terms of security, you should be safe from SQL injection since you are using parameterized queries as recommended.  That's true whether or not you validate the names using the regex.  Do not perform any additional escaping — that would only mangle your data.

That regex is for enforcing your business rules (i.e. you want to reject names written in Cyrillic, names with French accents like é, Irish surnames like O'Something), and has nothing to do with database security.

I do not recommend mixing PDO with the WordPress database API.

The WordPress documentation recommends that you use $wpdb->insert() for simple INSERT queries.

In accordance with the WordPress documentation, you should check the return value from $wpdb->query() — a FALSE value indicates failure.  You should do that before declaring victory with echo json_encode(['status' => true]);.

if (!empty($errors)) {
    echo json_encode(['status' => false, 'errors' => $errors]);
} elsif (FALSE === $wpdb->insert('people', ['name' => $_POST['name']], '%s')) {
    echo json_encode(['status' => false, 'errors' => ['Database error: ' . $wpdb->last_error]]);
} else {
    echo json_encode(['status' => true]);
}


Extract, filter and match three letters from the given arguments and predict the name Case 1: rank1_naming

This function takes two arguments

list_proteins_pattern_available
best_match_protein_name

  Objective: Extract the three letter pattern from the both arguments.
  Match the pattern and keep only the matched items. Extract the numbers
  from list_proteins_pattern_available and also sort it. Find the
  maximum number from the collected numbers and add 1 to get the next
  number.

Please let me know if you have any questions.

Can you point ways to improve this script?

import re

def case_rank1_naming(list_proteins_pattern_available, best_match_protein_name):
    #This will store the list of numbers
    available_list_numbers = []

    #extract the three letter pattern
    protein_pattern = re.search(r"[A-Z]{1}[a-z]{2}", best_match_protein_name)
    protein_pattern = protein_pattern.group()

    #extract the numbers
    for name in list_proteins_pattern_available:
        pattern = re.search(r"[A-Z]{1}[a-z]{2}\d{1,3}", name)
        number = re.search(r"\d{1,3}", pattern.group())
        available_list_numbers.append(number.group())

    #Convert all the string numbers to integers
    available_list_numbers = [int(x) for x in available_list_numbers]

    #Sort the available number. Just realized I use two times sort function.
    available_list_numbers.sort()

    # Sort the available number, get the maximum number and add one to get next number
    # Example: result will be 50
    primary_number_prediction = int(max(sorted(available_list_numbers))) + 1

    #Add the protein pattern, the next predicted number and 'Aa1' at the suffix
    predicted_name = protein_pattern + str(primary_number_prediction) + 'Aa1'

    return predicted_name

list_proteins_pattern_available = ['Xpp1Aa1', 'Xpp2Aa1', 'Xpp35Aa1', 'Xpp35Ab1', 'Xpp35Ac1', 'Xpp35Ba1', 'Xpp36Aa1', 'Xpp49Aa1', 'Xpp49Ab1']

best_match_protein_name = 'Xpp35Ba1'

predicted_name = case_rank1_naming(list_proteins_pattern_available, best_match_protein_name)

print(predicted_name)
#Xpp50Aa1

I'll show an example implementation first, and then describe it:

from typing import Iterable
import re

def case_rank1_naming(proteins_available: Iterable[str], best_match_protein_name: str) -> str:
    # extract the three-letter pattern
    protein_pattern = re.search(r"[A-Z][a-z]{2}", best_match_protein_name).group()

    # extract the numbers
    best_number = max(
        int(re.search(r"[A-Z][a-z]{2}(\d{1,3})", name)[1])
        for name in proteins_available
    )

    # Add the protein pattern, the next predicted number and 'Aa1' at the suffix
    return f'{protein_pattern}{best_number + 1}Aa1'

def main():
    proteins_available = (
        'Xpp1Aa1', 'Xpp2Aa1', 'Xpp35Aa1', 'Xpp35Ab1', 'Xpp35Ac1',
        'Xpp35Ba1', 'Xpp36Aa1', 'Xpp49Aa1', 'Xpp49Ab1'
    )
    best_match_protein_name = 'Xpp35Ba1'
    predicted_name = case_rank1_naming(proteins_available, best_match_protein_name)
    assert predicted_name == 'Xpp50Aa1'

if __name__ == '__main__':
    main()

Add type hints to better-define your function signature
Don't write {1} in a regex - you can just drop it
Call max immediately on a generator rather than making and sorting a list
Shorten your variable names. Especially don't include the type of the variable in its name. Type hints and appropriate pluralization will cover you instead.
Use f-strings
Have a main function
In main, use a tuple for proteins_available instead of a list because it doesn't need to mutate


Java Dice Roller with GUI Three days ago I wrote about a Java Dice Roller I wrote. I've now added a GUI to that program. Here it is:

DiceRollerGUI.java:

package com.egroegnosbig.dicerollergui;

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

public class DiceRollerGUI {
    static JFrame frameOne = new JFrame("Dice Roller");
    public static void main(String[] args) {
        frameOne.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        DiceGUI GUI = new DiceGUI();
        frameOne.add(GUI);

        Button b = new Button("Roll");
        b.addActionListener(new ButtonAction());
        frameOne.add(b);
        frameOne.setLayout(new GridLayout(1, 2));
        frameOne.setSize(400, 250);
        frameOne.setResizable(false);
        frameOne.setVisible(true);
    }
}

class ButtonAction implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        DiceRollerGUI.frameOne.setVisible(false);
        JFrame frameTwo = new JFrame("Dice Roller");
        frameTwo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frameTwo.setSize(400, 250);
        frameTwo.setResizable(false);
        ResultGUI resultGUI = new ResultGUI();
        frameTwo.add(resultGUI);
        frameTwo.setVisible(true);
    }
}

DiceGUI.java:

package com.egroegnosbig.dicerollergui;

import java.awt.*;
import javax.swing.*;

public class DiceGUI extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        this.setBackground(Color.WHITE);

        g.drawString("Dice Roller", 70, 20);
    }
}

ResultGUI.java:

package com.egroegnosbig.dicerollergui;

import java.awt.*;
import javax.swing.*;

public class ResultGUI extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        this.setBackground(Color.WHITE);

        Dice dice = new Dice(6);
        int resultInt = dice.roll();
        StringBuilder sb = new StringBuilder();
        sb.append("");
        sb.append(resultInt);
        String result = sb.toString();
        g.drawString("The dice rolled a", 150, 125);
        g.drawString(result, 243, 125);
    }
}

Dice.java:

package com.egroegnosbig.dicerollergui;

import java.util.Random;

public class Dice {
    private final Random rand;
    private final int faces;

    public Dice(int faces) {
        this.rand = new Random();
        this.faces = faces;
    }

    public int roll() {
        return rand.nextInt(faces) + 1;
    }
}

Working on better class names...

Rather than swapping out the entire JFrame for another on the button click, you should simply be updating the contents.  This is all very overwrought.  I think all you really need is a panel with a button and a label.  Click the button, and display the results in the label.
Related to the above, rather than overriding paint, you should be using a layout and adding subcomponents.

To get you started:

public class DicePanel extends JPanel {
  private final Dice dice;

  private JButton rollButton;
  private JLabel displayLabel;

  public DicePanel(Dice dice) {
    this.dice = dice;

    rollButton = new JButton("Roll");
    displayLabel = new JLabel();

    rollButton.addActionListener(e ->
      displayLabel.setText("You rolled a: " + dice.roll())
    );
    // or if you're not using Java 8, you can do the more verbose thing.

    // not specifying a layout defaults to a flow layout.  Set a layout via:
    // setLayout(new BorderLayout()); // or whatever
    add(rollButton);
    add(displayLabel);
  }
}

Your program should just create a Dice, create a DicePanel with that, and stick it in a JFrame and show it.  Then play around with layouts to get something you like.


Basic event stopPropagation() example - a better way of doing so? I've got a very very basic demo here that uses the .stopPropagation method. I want to just make it so that clicking on the parent element only runs the function, so I assumed I could use e.stopPropagation() as in the commented out line in the example below. However, that fails, which meant I had to apply the stopPropagation() method to the child element to prevent clicking on the child activating the initial click function.
Is this really the right way of doing this, or is there a better way? Something doesn't feel right here. Thanks for any help - the code is below

var test = document.getElementById('test'),
    child = document.getElementById('child');

test.addEventListener('click', function (e) {
  //e.stopPropagation();
  console.log('click');
});

child.addEventListener('click', function (e) {
  e.stopPropagation();
  console.log('clicked child - is there a better way of using e.stopPropagation() ?');
});
#test {
  background: red;
  display: flex;
  position: relative;
  height: 30px;
  width: 100%;
}
#child {
  background: pink;
  margin-top: 5em;
  position: absolute;
}

child

CodePen: https://codepen.io/ns91/pen/wvayqaE

Your Question

Is this really the right way of doing this, or is there a better way? Something doesn't feel right here.

The term "better" is subjective so you can judge for yourself. Presuming there is not a need to have clicks on the child elements trigger any event handlers, one alternative is to use the CSS property pointer-events style. One could use the value none:

none
The element is never the target of pointer events; however, pointer events may target its descendant elements if those descendants have pointer-events set to some other value. In these circumstances, pointer events will trigger event listeners on this parent element as appropriate on their way to/from the descendant during the event capture/bubble phases.

var test = document.getElementById('test'),
    child = document.getElementById('child');

test.addEventListener('click', function (e) {
  console.log('click on parent without stopping propagation');
});
#test {
  background: red;
  display: flex;
  position: relative;
  height: 30px;
  width: 100%;
}
#child {
  background: pink;
  margin-top: 5em;
  position: absolute;
  pointer-events: none;
}

child


Python date formatter I'd like to find the best way to format date to YYYY, YYYYMM or YYYYMMDD.
Here is what I've got so far:

# gets the position of a character in the format
def get_pos(format, letter, number):
    it_number = 0
    it_pos = 0
    for char in format:
        if char == letter:
            it_number += 1
            if it_number == number:
                return(it_pos)
        it_pos += 1
    return(-1)

# loops through all the characters forming a number
def format_loop(string, old_format, letter):
    new = ''
    pos = -2
    it = 1
    while(pos != -1):
        pos = get_pos(old_format, letter, it)
        if(pos >= 0):
            new += string[pos]
        it += 1
    return(new)

# format a date
def date_format(string, old_format, new_format, delim):
    new = format_loop(string, old_format, 'Y')
    if(new_format in 'MD'):
        new += delim + format_loop(string, old_format, 'M')
    if(new_format == 'D'):
        new += delim + format_loop(string, old_format, 'D')
    return(new)

The function's intake parameters are, in order, the date string to format, its current format, the desired format in the form of 'Y', 'M' or 'D' and an optional delimiter to put in between the numbers.

I'm open for suggestions on shortening and optimising the code as well as on coding style and variables/functions naming.

For the first loop, there is a neat little function called enumerate() which allows you to iterate through an object and access both the element and the iteration number.

You can also remove various parenthesis, for the returned value and also for the while loop (although for big conditions it's handy to keep the parenthesis sometimes).

def get_pos(format, letter, number):
    it_number = 0
    # it_pos = 0 <--- not needed anymore because of the
    for it_pos, char in enumerate(format): # <--- enumerate
        if char == letter:
            it_number += 1
            if it_number == number:
                return it_pos
        # it_pos += 1 <--- same thing here
    return -1

For the second function I would suggest to use while True and break so that you don't have to declare pos=-2 beforehand.

def format_loop(string, old_format, letter):
    new = ''
    # pos = -2 <--- replaced by a break
    it = 1
    while True:
        pos = get_pos(old_format, letter, it)
        if pos == -1:
            break
        elif pos >= 0:
            new += string[pos]
        it += 1
    return new

Also, I don't know if there is an official recommendation on that, but I like to use very explicit return values for special cases, for example the string "not found" instead of -1. That makes the code more English than Python when you read if pos=="not found": break and I rather like that.


Guess the computer's number using functions I am looking to improve the Python Number Guessing Game program:

How is the overall structure of the code?
Have I used functions to the best of their ability?
Can the code be simplified? If yes, please feel free to show how.
The replay_game() function especially seems un-pythonic and overkill.

# Guess My Number Game
# MacOSX (Latest), Python 3.4.3, 27/08/2017
# Guess The Computers number between 1-100

from random import randint
from time import sleep

def gen_number():
    random_number = randint(0, 101)
    return random_number

def intro():
    print("Welcome to, Guess My Number!")
    print("Simply guess the number between 1-100 that the Computer is 'thinking' of!")
    print()

def ask_number(question, random_number):
    response = None
    while response != random_number:
        try:
            response = int(input(question))
            if response > random_number:
                print("Lower... ")
            elif response < random_number:
                print("Higher... ")
            else:
                correct = response
                congrat_winner(correct, random_number)
        except ValueError:
                print("Invalid. Enter a number between 1-100 ")
    return response

def human_guess():
    print("Ok Human! Let's begin... ")
    sleep(1)
    random_number = gen_number() # Named the variable random_number, the same as the variable in gen_number(). Is this good practise?
    guess = ask_number("Guess the number: ", random_number)

def congrat_winner(correct, random_number):
    if correct == random_number:
        print()
        print("Calculating results...")
        sleep(1)
        print()
        print("WELL DONE!")
        print("The answer was indeed,", str(correct) + "!")

def replay_game():
    replay_question = None
    while replay_question != 'y' or 'n':
        replay_question = input("Would you like to play again (y/n)? ").lower()
        if replay_question == 'y':
            print()
            print("Rebuilding game... ")
            main()
        elif replay_question == 'n':
            print("Goodbye!")
            exit()
        else:
            print("please enter either 'y' or 'n'... ")

def main():
    intro()
    human_guess()
    replay_game()

main()

There is a classic problem in this condition:

while replay_question != 'y' or 'n':

It always evaluates to True since string n is always truthy.

And, here is a set of code style violations I would work on:

guess variable inside the human_guess() function is unused
keep 2 blank lines between the function definition (PEP 8 - Style Guide)
put the main() function call into under the if __name__ == '__main__':
the print("Invalid. Enter a number between 1-100 ") is overly indented with 8 spaces, use 4 spaces
you can use a multi-line string for your intro message:

print("""
Welcome to, Guess My Number!
Simply guess the number between 1-100 that the Computer is 'thinking' of!
""")


Count comments and lines of code I wrote a small script as an answer for a Stack Overflow question, which referred to counting lines of code and comments (in C and C++ style).

f = File.open("test.txt")

loc = 0
comments = 0
while line = f.gets
  if commented ||= line.match(/^\/\*/)
    commented = nil if line.match(/\*\/$/)
    comments += 1
  elsif line.match(/^\s*\/\//)
    comments += 1
  else
    loc +=1 unless line.match(/^\s*\n/)
  end
end

puts loc
puts comments

I'm just looking for a review.

Your code looks pretty good to me, only that it's very imperative. I know it's not for everybody's taste, but a functional approach on text processing is also feasible.

My take: you start by defining an object (which may be a hash) to store the state (needed for in intermediate iterations and the final result), and then fold (reduce/inject) over the input lines, returning the next state on each step.

There are some edge cases (lines with multiple or nested comment) which I won't consider, let's keep it simple. I'd write:

initial_state = {lines: 0, comments: 0, in_multiline_comment: false}
final_state = open("test.txt").lines.inject(initial_state) do |state, line|
  state_update = if state[:in_multiline_comment]
    {comments: state[:comments] + 1, in_multiline_comment: !line.match(/\*\//)}
  else
    case line
    when /\/\*/
      {comments: state[:comments] + 1, in_multiline_comment: !line.match(/\*\//)}
    when /\/\//
      {comments: state[:comments] + 1}
    else
      {lines: state[:lines] + (line.strip.empty? ? 0 : 1)}
    end
  end
  state.merge(state_update)
end

Notice that you don't worry about stateful variables anymore, we just think "if I have this input and this current state, what output would I want?". Once you've covered all scenarios, the algorithm is done (hopefully leaving behind a declarative and maintainable code).


Meteor jquery-ui slider integration I'm struggling to integrate a jquery-ui slider widget into my Meteor app. The idea is to have a slider value in a Mongo collection and the slider needs to be reactive (automatically synced between clients). I've achieved this and it works but the implementation is not very elegant and clean. It's quite hard to maintain, test and extend such code. I've achieved this via Tracker.autorun and jquery slider slide handle (_.throttle is used to limit mongo update interval).

I'm new to Meteor, and it's awesome, but so far couldn't find better way to implement this (which I bet exists):

Live example

Slider = new Meteor.Collection("Slider");

if (Meteor.isClient) {
    Template.slide.rendered = function() {
        var handler = _.throttle(function(event, ui) {
            var val = Slider.findOne({});
            Slider.update({ _id: val._id }, {$set: {slide: ui.value}});
        }, 50, { leading: false });

        if (!this.$('#slider').data('uiSlider')) {
            $("#slider").slider({
                 slide: handler
            });
        }

        Tracker.autorun(function() {
            var slider = Slider.findOne({});
            if (slider) {
                this.$('#slider').data('uiSlider').value(slider.slide);
            }
        });
    };
}

//seed Collection
if (Meteor.isServer) {
    if (Slider.find().count() == 0) {
        Slider.insert({
            slide: 20
        });
    }
}

HTML

jquery-ui slider test

   {{> slide}}

<template name="slide">

</template>

I think you can avoid the Tracker.autorun completely by updating the value in a template helper -- this is possible because your data is coming from a Collection, so it's already reactive.  You can play around with it in this MeteorPad, but a brief summary follows:

<template name="slider">

  Slider's current value is...{{sliderVal}}
</template>

//JS -- ommitted the rendered bit, which looks identical to yours w/o the Tracker.autorun
Template.slider.helpers({
  sliderVal:  function() {
    var slider = Slider.findOne(); // this guy is reactive, so when another client updates the Collection, it'll get pushed to us
    if (slider) {           Template.instance().$('#slider').data('uiSlider').value(slider.slide); // Template.instance() b/c `this` doesn't return a template instance in a helper
      return slider.slide; // again, here you can return nothing if you'd rather have no text
    }
  }
});


Convert seconds to hours, minutes and seconds My logic is as follow:

Convert actual time to minutes.
Extract seconds from minutes (30:04 -> 4 seconds).
Subtract seconds value from minutes (step1-step2) to get time only in seconds.
Convert time in minutes (step 3 output/60) to hours.

Now suppose i got time as 5404 which corresponds to 1:30:04. When I divide 5404, I get value as 90.0666666667. 0666666667 is actually 4 seconds to get value as 4 seconds. I convert the data to 60 unites by using percentage formula i.e

value * 60 / 100

I know there is a better solution here.

import java.math.BigDecimal;
import java.math.RoundingMode;

public class TimeCalc {

    public static void main(String[] args) {

        // Inital Time in seconds
        BigDecimal actualTime = new BigDecimal(5404);

        // 60 seconds
        BigDecimal seconds = new BigDecimal(60);

        // dividing original time to get time in mintues
        BigDecimal timeinMinutes = actualTime.divide(seconds, 2, RoundingMode.CEILING);

        // to get value of seconds from minutes
        double secondsValue = timeinMinutes.doubleValue() - Math.floor(timeinMinutes.doubleValue());

        // Seconds will be removed from Minutes to get only Minutes value
        BigDecimal deductiableSecondValue = new BigDecimal(secondsValue);
        timeinMinutes = timeinMinutes.subtract(deductiableSecondValue);
        timeinMinutes = new BigDecimal(Math.ceil(timeinMinutes.doubleValue()));

        // dividing minutes by 60 to get actual time in hours
        BigDecimal timeinHours = timeinMinutes.divide(seconds, 2, RoundingMode.CEILING);
        double hoursdecimalValue = timeinHours.doubleValue();

        // suppose time is 1.30 , below code is to get the 30 minutes
        double minutes = hoursdecimalValue - Math.floor(hoursdecimalValue);

        // converting value in units of Time since it is always measured wrt 60
        minutes = convertDateinTimeUnit(minutes);

        // suppose time is 1.30 below code is get 1 value
        String str = new Double(hoursdecimalValue).toString();
        str = str.substring(0, str.indexOf('.'));
        double v = Double.valueOf(str);

        // converting value in units of Time since it is always measured wrt 60
        secondsValue = convertDateinTimeUnit(secondsValue);

        secondsValue = Math.ceil(secondsValue);

        minutes = Math.ceil(minutes);

        System.out.println(" secondsValue " + secondsValue);
        System.out.println(" minutes decimal value " + minutes);
        System.out.println(" hours " + v);

    }

    static double convertDateinTimeUnit(double value) {
        double valueInTimeUnit = 60 * value / 100;
        return valueInTimeUnit * 100;

    }

}

// Inital Time in seconds
        BigDecimal actualTime = new BigDecimal(5404);

Why store this in a BigDecimal?  First, you aren't including a fractional part.  Second, it's just not that big.  The thirty-one bits of an int is enough for almost seventy years worth of seconds.  Sixty-three bits (long) is enough for over two hundred billion years of seconds.  You're only producing hours as output.  If you need more than twenty bits, you should probably add at least days if not weeks.

        BigDecimal seconds = new BigDecimal(60);

This seems like a constant, which you would probably define outside the function.

         private final static int SECONDS_PER_MINUTE = 60;

I also find the name misleading.  When I see seconds, I don't think that there are sixty seconds in a minute.  I think that this is the seconds portion of the time.

Don't put everything in main

You have more logic in your main method than you should.  Part of what makes the other solution better is that it only has two lines in its main method.  As a general rule, you want to put all your programming logic in other methods.  The main method should just handle input, output, and calling the methods that do the real work.

Why do floating point operations?

        // dividing original time to get time in mintues
        BigDecimal timeinMinutes = actualTime.divide(seconds, 2, RoundingMode.CEILING);

        // to get value of seconds from minutes
        double secondsValue = timeinMinutes.doubleValue() - Math.floor(timeinMinutes.doubleValue());

You don't need floating point operations here.  You're essentially approximating fast integer operations with slower floating point operations.

        int seconds = actualTime;
        int minutes = seconds / SECONDS_PER_MINUTE;
        seconds %= SECONDS_PER_MINUTE;

This also gets rid of all the extraneous doubleValue() and Math.floor calls.

Note that the use of doubleValue reinforces the point that you don't need BigDecimal.  If all your values fit into a double without loss of precision, why put them into a BigDecimal?

This may work.  But I would be worried that the rounding would sometimes cause the wrong value.  Particularly since two decimal digits make a repeating fractional part in binary.  Perhaps there's no value that makes this not work, but why take that chance?

Don't repurpose constants by value

        // dividing minutes by 60 to get actual time in hours
        BigDecimal timeinHours = timeinMinutes.divide(seconds, 2, RoundingMode.CEILING);

This is just horrible.  It would be better to just say 60 than reuse seconds to mean the number of minutes in an hour.

Eek

        // suppose time is 1.30 , below code is to get the 30 minutes

If the hours are 1.30, then that .30 is not 30 minutes.  It's 18 minutes.

        double minutes = hoursdecimalValue - Math.floor(hoursdecimalValue);

        // converting value in units of Time since it is always measured wrt 60
        minutes = convertDateinTimeUnit(minutes);

and

    static double convertDateinTimeUnit(double value) {
        double valueInTimeUnit = 60 * value / 100;
        return valueInTimeUnit * 100;

    }

Other than potentially odd rounding effects, the net effect of this method is to multiply value by 60.  I'm not sure what you think is happening here, but you are just multiplying by sixty (with some loss of precision).

A side issue is that this only works for seconds and minutes expressed as fractions of minutes and hours respectively.  I'm not sure why you mention "Date" at all.

The camelCase standard has you capitalizing every word after the first, so this would more normally be written convertDateInTimeUnit.

Use Math.floor to truncate

        // suppose time is 1.30 below code is get 1 value
        String str = new Double(hoursdecimalValue).toString();
        str = str.substring(0, str.indexOf('.'));
        double v = Double.valueOf(str);

You could have just said

        double hours = Math.floor(hoursDecimalValue.doubleValue());

and saved the extra overhead of converting to and from a string.  Especially since you were already using Math.floor to calculate this value.

You're essentially reinventing

        int hours = minutes / MINUTES_PER_HOUR;
        minutes %= MINUTES_PER_HOUR;

Only you're using a lot more code that only approximates these values.  If you want the integer mathematics behavior, why not just work with integers?

Binary division

When you store .1 as a binary value, it gets store as a series of bits.  Decimal 10 is 1010 in binary.  So

$$1 / 1010_2 = .0001100110011...$$

Since it repeats, it means that it may not convert back perfectly.  For example, if you round to four binary digits, it is .0001 or .0010 (depending on whether you round down or up).  The first of those is one sixteenth and the latter is one eighth.  If you round to five binary digits, it is .00011, which is exactly 3/32.

Anyway, take .1 and .2, convert to binary rounded to four digits (round up if the next digit is a 1), and then add them.  So .0010 + .0011 = .0101, which is 5/16 or .3125.  You're already off by an eightieth.  You could be off less with more digits, but you'll still be off by some small amount.

When you do all your roundabout math operations, these errors are building (and occasionally dropping).  I would be concerned that you will occasionally get the wrong answer if you pick a value where it builds errors more than it drops them.


Merge sort a list of integers This code is meant to sort a list of integers using merge sort.

I'm doing this to improve my style and to improve my knowledge of fundamental algorithms/data structures for an upcoming coding interview.

def merge_sort(l):
    if len(l) == 0 or len(l) == 1:
        return

    mid = len(l) // 2
    left = l[:mid]
    right = l[mid:]
    merge_sort(left)
    merge_sort(right)
    merge(l, left, right)

def merge(l, left, right):
    l_ind, r_ind, ind = 0, 0, 0
    left_len, right_len, l_len = len(left), len(right), len(l)

    while l_ind < left_len and r_ind < right_len:
        if left[l_ind] < right[r_ind]:
            l[ind] = left[l_ind]
            l_ind += 1
            ind += 1
        else:
            l[ind] = right[r_ind]
            r_ind += 1
            ind += 1

    if l_ind < left_len and r_ind >= right_len:
        while ind < l_len:
            l[ind] = left[l_ind]
            l_ind += 1
            ind += 1
    elif l_ind >= left_len and r_ind < right_len:
        while ind < l_len:
            l[ind] = right[r_ind]
            r_ind += 1
            ind += 1

Get rid of some len

left_len, right_len, l_len = len(left), len(right), len(l)

Get rid of these, they don't do anything in terms of readability. They also are unnecessary, the len call is not O(n) it is simply O(1).

(Maybe) a library?

Also, although Rosetta code isn't always the most stylistic source, if you look at their solution, the use a pre-built merge. As you say you are "reinventing the wheel", maybe you don't want to do that but something to consider in the future.

Naming

l_ind, r_ind ...

I would write those out in full as left_ind and right_ind.


Sum of proper divisors of every number up to N I wrote a function which provides the sum of proper divisors of every number up-to N (N is a natural number) and I want to improve its performance.

For example, if N = 10 then the output is:

[0, 0, 1, 1, 3, 1, 6, 1, 7, 4, 8]

This is my proper divisor sum function:

def proper_divisor_sum(N):
    N += 1
    divSum = [1] * N
    divSum[0], divSum[1] = 0, 0
    for i in range(2, N//2+1):
        for j in range(i+i, N, i):
            divSum[j] += i
    return divSum

I am certain that there is an algorithmic/mathematical optimization for this problem but I am having trouble thinking about it because I am not good at math.

1. Analysis

The code in the post loops over \$2 ≤ i ≤ {n\over 2}\$ and then over the multiples of \$i\$ below \$n\$:

for i in range(2, N//2+1):
    for j in range(i+i, N, i):
        div_sum[j] += i + j//i if i != j//i else i  # (A)

This means that the line (A) is executed at most $$ {n\over 2} + {n\over 3} + {n\over 4} \dotsb + {n \over n/2} $$ times, that is $$ n\left({1\over 2} + {1\over 3} + {1\over 4} \dotsb {1\over n/2}\right) $$ which is \$n(H_{n/2} - 1)\$ (where \$H_n\$ is the \$n\$th harmonic number), and this is \$Θ(n \log n)\$.

2. Improvement

The first thing to note is that if we had a function that computed the sum of all the divisors, then we could compute the sum of proper divisors by subtracting the number itself:

def sum_proper_divisors(n):
    """Return list of the sums of proper divisors of the numbers below n.

    >>> sum_proper_divisors(10) # https://oeis.org/A001065
    [0, 0, 1, 1, 3, 1, 6, 1, 7, 4]

    """
    result = sum_divisors(n)
    for i in range(n):
        result[i] -= i
    return result

Let's call the sum-of-all-divisors function \$σ\$, and consider for example \$σ(60)\$: $$ σ(60) = 1 + 2 + 3 + 4 + 5 + 6 + 10 + 12 + 15 + 20 + 30 + 60. $$ Collect together the divisors by the largest power of 2 in each divisor: $$ \eqalign{σ(60) &= (1 + 3 + 5 + 15) + (2 + 6 + 10 + 30) + (4 + 12 + 20 + 60) \\ &= (1 + 3 + 5 + 15) + 2(1 + 3 + 5 + 15) + 2^2(1 + 3 + 5 + 15) \\ &= (1 + 2 + 2^2)(1 + 3 + 5 + 15).} $$ Now, the remaining factor \$1 + 3 + 5 + 15\$ is \$σ(15)\$ so we can repeat the process, collecting together the divisors by the largest power of 3: $$ \eqalign{σ(15) &= (1 + 5) + (3 + 15) \\ &= (1 + 3)(1 + 5).}$$ And so $$ σ(60) = (1 + 2 + 2^2)(1 + 3)(1 + 5). $$ This is obviously connected to the fact that \$ 60 = 2^2·3·5 \$. In general, if we can factorize \$n\$ as: $$ n = 2^a·3^b·5^c\dotsb $$ then $$ σ(n) = (1 + 2 + \dotsb + 2^a)(1 + 3 + \dotsb + 3^b)(1 + 5 + \dotsb + 5^c)\dotsm $$ These multipliers occur many times, for example \$(1 + 2 + 2^2)\$ occurs in the sum of divisors of every number divisible by 4 but not by 8, so it's most efficient to sieve for the sums of many divisors at once, like this:

def sum_divisors(n):
    """Return a list of the sums of divisors for the numbers below n.

    >>> sum_divisors(10) # https://oeis.org/A000203
    [0, 1, 3, 4, 7, 6, 12, 8, 15, 13]

    """
    result = [1] * n
    result[0] = 0
    for p in range(2, n):
        if result[p] == 1: # p is prime
            p_power, last_m = p, 1
            while p_power < n:
                m = last_m + p_power
                for i in range(p_power, n, p_power):
                    result[i] //= last_m    # (B)
                    result[i] *= m          # (B)
                last_m = m
                p_power *= p
    return result

3. Analysis

The lines marked (B) are executed at most $${n\over 2} + {n\over 2^2} + \dotsb + {n\over 3} + {n\over 3^2} + \dotsb $$ times, that is $$n\left({1 \over 2} + {1 \over 2^2} + \dotsb + {1\over 2^{\lfloor \log_2 n\rfloor}} + {1 \over 3} + {1 \over 3^2} + \dotsb + {1\over 3^{\lfloor \log_3 n\rfloor}} + \ldots\right)$$ which is less than $$n\left({1\over 2-1} + {1\over3-1} + {1\over5-1} + \dotsb + {1\over p-1}\right)$$ where \$p\$ is the largest prime less than or equal to \$n\$, and this is \$Θ(n \log \log n)\$ (see divergence of the sum of the reciprocals of the primes) and so asymptotically better than the code in the post.


Cloning Entity Framework entities I'm currently writting piece of logic which copies entities from one user account to another. My current strategy in doing this is like that:
Consider the following code:

 public class MobileOrderSettings:ICloneable
{
    public long Id { get; set; }
    public bool allowCash { get; set; }
    public int deliveryPrice { get; set; }
    public int deliveryTreshold { get; set; }
    public bool orderingEnabled { get; set; }
    public bool paymentsEnabled { get; set; }
    public int shippingType { get; set; }

    public virtual MobileApp MobileApp { get; set; }

    public object Clone()
    {
        var copy = CopyUtils.ShallowCopyEntity(this);
        copy.Id = default(int);
        copy.MobileApp = null;
        return copy;
    }
}

The ShallowCopyEntity method defined like in this way:

 public static TEntity ShallowCopyEntity<TEntity>(TEntity source) where TEntity : class, new()
    {

        // Get properties from EF that are read/write and not marked witht he NotMappedAttribute
        var sourceProperties = typeof(TEntity)
                                .GetProperties()
                                .Where(p => p.CanRead && p.CanWrite &&
                                            p.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.Schema.NotMappedAttribute), true).Length == 0);
        var notVirtualProperties = sourceProperties.Where(p => !p.GetGetMethod().IsVirtual);
        var newObj = new TEntity();

        foreach (var property in notVirtualProperties)
        {

            // Copy value
            property.SetValue(newObj, property.GetValue(source, null), null);

        }

        return newObj;

    }

So, as you can see, I firstly copy all fields which is not virtual, reassing Id value and then perform copy of the dependent object(collection)(In this particular situation MobileOrderSettings depends on MobileApp entity, so I make MobileApp null, and in MobileApp Clone menthod I assign MobileOrderSettings virtual field the copy of MobileOrderSettings). Is this approach is good, or you can suggest any better solution?

Two possible sources of errors:

If you forget to use (or don't want to apply) the virtual modifier, it will no longer be a shallow copy (because virtual is typically used for navigation properties).
It relies on unmapping properties by attributes. If at any time in the future you start using the fluent API for that purpose you'll change behavior in an unexpected place.

You evidently want to clone mapped and scalar properties only. Your approach works (if you remember the error sources), but I'd prefer to use a method provided by EF itself:

MobileOrderSettings settings = context.MobileOrderSettings.FirstOrDefault();
var shallowCopy = (MobileOrderSettings)context.Entry(settings)
                                              .CurrentValues.ToObject()

As you see, the CurrentValues property of an entry in EF's change tracker is used to build a clone, which is always a shallow clone of mapped properties.

Of course, you can't apply this method inside an entity class, because it requires a context to which the entity object is attached. But is that bad? I'd say no, because this clone method has a very specific purpose which is tied to an EF environment. To me it would break the persistence ignorance principle if a class would require knowledge of the data layer implementation for which it clones itself.


Determine final player in a counting game I made a function in which 17 players are counting to number N. Function as a parameter takes a number N and returns which player is going to say N. If current number is divisible by 9 the counting order is reversed, and if current number is divisible by 17 the next player is skipped. I made this code, but is a little bit too big for me, so I wonder if there is another (less code) way I could solve it.
func playertold(number: Int)  {

var currentNumber:Int = 1
var currentPlayer:Int = 1
var reversedOrder:Bool = false

while currentNumber != number {

    if currentNumber % 9 == 0 {

        reversedOrder = !reversedOrder

    }

    if  currentNumber % 17 == 0 {
        if reversedOrder {
            if currentPlayer == 2 {
                currentPlayer = 17
            } else if currentPlayer == 1 {
                currentPlayer = 16
            } else {
                currentPlayer -= 2
            }
        } else{
            if currentPlayer == 16 {
                currentPlayer = 1
            }else if currentPlayer == 17 {
                currentPlayer = 2
            }else {
                currentPlayer += 2
            }
        }
    } else {

    if reversedOrder {
        currentPlayer -= 1

        if currentPlayer < 1 {
            currentPlayer = 17
        }
    } else {
        currentPlayer += 1

        if currentPlayer > 17 {
            currentPlayer = 1
        }
    }
    }

    currentNumber += 1

}

print("Player who will say number \(number) is \(currentPlayer)")
}

General remarks

The computation should be separated from the program output. That increases the clarity of the program, and makes the functions better testable. In your case, func playertold should return the result instead of printing it.

Type annotations are often not needed, e.g.
var currentNumber:Int = 1
var currentPlayer:Int = 1
var reversedOrder:Bool = false

can be simplified to
var currentNumber = 1
var currentPlayer = 1
var reversedOrder = false

The indending and spacing it not consistent: The function body and some blocks are not indented, some empty lines are superfluous.

Simplify the program logic
The while-loop
var currentNumber:Int = 1
while currentNumber != number {
    // ... do something ...
    currentNumber += 1
}

can be simplified to a for-loop over a range:
for currentNumber in 1..<number {
    // ... do something ...
}

Instead of a boolean variable reversedOrder you can use a integer variable direction which holds the values +1 or -1. Advancing to the next player is then done with
currentPlayer += direction
// or:
currentPlayer += 2 * direction

depending on whether the next player is skipped or not. After updating the currentPlayer one can check for wrap-around. That saves a lot of case distinctions.
Instead of the remainder operator % can can use the isMultiple(of:) method which was introduced in Swift 5, which expresses the intent better.
The function would then look like this:
func playertold(number: Int) -> Int {
    var currentPlayer = 1
    var direction = +1

    for currentNumber in 1..<number {
        if currentNumber.isMultiple(of: 9) {
            direction = -direction
        }
        // Advance position:
        if currentNumber.isMultiple(of: 17) {
            currentPlayer += 2 * direction
        } else {
            currentPlayer += direction
        }
        // Check for wrap-around:
        if currentPlayer < 1 {
            currentPlayer += 17
        } else if currentPlayer > 17 {
            currentPlayer -= 17
        }
    }
    return currentPlayer
}

More suggestions
Avoid “magic constants.” In this function that are the numbers 9 and 17, and the latter has two different meanings. What if you want to change the number of players from 17 to 20? In your original code you would have to replace multiple instances of 16 and 17, and in the above version you still have to multiple instances of 17 – but not the 17 in the isMultiple(of: 17) check! That is too error-prone.
One option is to define constants, e.g.
let numPlayers = 17
let reversePosition = 9
let skipPosition = 17

Another – more flexible – option is to make these additional parameters of the function, with default values:
func playertold(number: Int, numPlayers: Int = 17,
                reversePosition: Int = 9, skipPosition: Int = 17) -> Int {
    var currentPlayer = 1
    var direction = +1

    for currentNumber in 1..<number {
        if currentNumber.isMultiple(of: reversePosition) {
            direction = -direction
        }
        // Advance position:
        if currentNumber.isMultiple(of: skipPosition) {
            currentPlayer += 2 * direction
        } else {
            currentPlayer += direction
        }
        // Check for wrap-around:
        if currentPlayer < 1 {
            currentPlayer += numPlayers
        } else if currentPlayer > numPlayers {
            currentPlayer -= numPlayers
        }
    }
    return currentPlayer
}

Now the intent of every constant is clear. The function can still be called with
the standard values
print(playertold(number: 1234))

but also with custom values
print(playertold(number: 1234, numPlayers: 20, reversePosition: 5, skipPosition: 15))


Is this a good way to receive a message from a server? I am developing some software that uses a pretty ancient low-level TCP/IP protocol from (I think) the eighties. I can send messages to the server very reliably, but I am a little unsure about receiving them. I cannot predict when the server will send me a message, so I have this method in an infinite loop. GetNextMessage() blocks the thread until it receives a message, whereupon the message is acted upon, and the loop repeats.

Messages are sent at a rate of about maybe 5 or 6 a minute, and I can process them in less than a quarter of a second, so I'm not currently spinning off a new thread when I receive them.

This code fragment contains all the relevant symbols and the logic that I am unsure of:

    /// this is filled earlier in the program
    private Socket _socket;

    private const int BufferSize = 4096;

    /// <summary>
    /// This byte (hex 02) indicates the start of the message.
    /// </summary>
    private const byte RecordStart = 2;

    /// <summary>
    /// This byte (hex 03) indicates the end of the message.
    /// </summary>
    private const byte RecordEnd = 3;

    private string GetNextMessage()
    {
        byte[] bytesReceived = new byte[BufferSize];

        // ReSharper disable PossibleNullReferenceException
        _socket.Receive(bytesReceived);
        // ReSharper restore PossibleNullReferenceException

        if (_socket.Poll(1, SelectMode.SelectRead))
        {
            throw new SocketException((int)SocketError.ConnectionReset);
        }

        IEnumerable<byte> bytes = bytesReceived
            .Where(character => character != RecordStart)
            .TakeWhile(character => character != RecordEnd);

        return Encoding.ASCII.GetString(bytes.ToArray());
    }

My concerns:

I am not sure if _socket.Poll() is the correct way to determine if the socket has gone away. It most certainly works and is very necessary, but I'm sure I should be doing something else.
I once performed an operation that sent three messages immediately after each other, but I only appeared to receive two of them. It is possible that there is a bug in the product I am developing for (seems likely), but I am worried that the method I have chosen is somehow causing messages to be discarded.

One thing I do with reading from sockets is separate receiving of the data from what the data contains.

Meaning, you may get your information in progressive chunks.....  so receive a chunk of data, then see if you have a complete "Message".  If not, wait for the next chunk of data.  When you have your full "Message"  then you can pass that on to whatever wants it.

In fact what I have done is abstract the idea of a streaming connection so I can interchange serial ports / tcp sockets / and any other streaming type connection.  Have something that receives from a connection, and then do interpreting.


find all anagrams of a given word I wrote this program which generates anagrams for a given word.
The init function will create a dictionary of words. it can be read from a text file or array. Here I'm reading words from an array to create my dictionary.
I would like some advice on how to optimize this code or any changes or suggestions needed to improve efficiency of this code is appreciated.

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

public class Solution {

    static Map<String, ArrayList<String>> dictionaryMap = new HashMap<String, ArrayList<String>>();

    private void addToMap(String key, String word) {
        ArrayList<String> anagramList = dictionaryMap.get(key);

        if (anagramList == null) {
            anagramList = new ArrayList<String>();
            anagramList.add(word);
            dictionaryMap.put(key, anagramList);

        }
        if (!anagramList.contains(word)) {
            anagramList.add(word);
            dictionaryMap.put(key, anagramList);
        }
    }

    private String createMap(String word) {
        Map<Character, Integer> characterCountMap = new HashMap<Character, Integer>();
        StringBuffer buff = new StringBuffer();
        char arr[] = word.toLowerCase().toCharArray();
        Arrays.sort(arr);
        String sortString = Arrays.toString(arr);
        for (int i = 0; i < sortString.length(); i++) {
            char c = sortString.charAt(i);
            if (characterCountMap.containsKey(c))
                characterCountMap.put(c, characterCountMap.get(c) + 1);
            else
                characterCountMap.put(c, 1);
        }

        for (Map.Entry<Character, Integer> entry : characterCountMap.entrySet())
            buff.append(entry.getKey() + entry.getValue());

        return buff.toString();
    }

    private Map<String, ArrayList<String>> init(String[] words) {
        for (String word : words) {
            addToMap(createMap(word), word);

        }
        return dictionaryMap;
    }

    private String[] getAnagrams(String word) {

        String key = createMap(word);
        List<String> al = dictionaryMap.get(key);
        String[] arr = al.toArray(new String[al.size()]);
        return arr;
    }

    public static void main(String[] args) {
        Solution obj = new Solution();
        System.out.println("This is a debug message");
        String arr[] = { "ate", "eat", "THIS", "EAT" };
        obj.init(arr);
        for (String anagram : obj.getAnagrams("tea"))
            System.out.println(anagram);

    }
}

Thanks for sharing your code.

This is what I think about it

General Coding

program against interfaces

Most of your variables are defines as concrete types (classes you actually instantiate).
You should better declare them as interface types so that it is possible to exchange
the concrete implementation without changing the code all over.

example

static Map<String, ArrayList<String>> dictionaryMap = new HashMap<String, ArrayList<String>>();

should better be

static Map<String, List<String>> dictionaryMap = new HashMap<String, ArrayList<String>>();

or even

static Map<String, Collection<String>> dictionaryMap = new HashMap<String, ArrayList<String>>();

Problem here is that you need to know what interfaces are available and what the
consequences are using them. The public API
is the place to find that information.

Be consistent

Choose the same approach for the same problem

E.g. you use two different types of loops

    for (int i = 0; i < sortString.length(); i++) {
        char c = sortString.charAt(i);
    //...
    // vs.
    for (String word : words) {
        addToMap(createMap(word), word);
    //...

Unless you really need the index variable for something else then accessing the actual
object in the collection loops over you could (and should) stick to the foreach
form

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

Learn about the capabilities of the objects provided by the runtime

Especially the class Map has some interesting methods your code could benefit from:
The code

    ArrayList<String> anagramList = dictionaryMap.get(key);
    if (anagramList == null) {
        anagramList = new ArrayList<String>();
        anagramList.add(word);
        dictionaryMap.put(key, anagramList);
    }

could be replaced by

    ArrayList<String> anagramList = dictionaryMap.computeIfAbsent(key,()->new ArrayList<String>());

If you would know that beside (Array-)List which allows duplicates, the Java
Runtime provides another collection type Set which does not hold duplicates, then
you could even get rid of the other if in this method too:

static Map<String, Collection<String>> dictionaryMap = new HashMap<String, Collection<String>>();

private void addToMap(String key, String word) {
    dictionaryMap.computeIfAbsent(key,()-> new HashSet<String>())
                 .add(word);
 }

Avoid arrays

instead of arrays better use Collection types like any implementations of the List
and  Set interfaces. They are more flexible and prevent you to copy data (yourself)
when its size needs to be changed.

use the static key word with intention

You declared the variable dictionaryMap as a class variable although it is not
accessed by any  static method. Unless you understand the consequences you should not use the static key word.

narrow your interfaces

Your method init() has a return value which is not needed since there is no caller
of this method dealing with this return value. Methods with return value usually
are harder to refactor. Especially its harder to split them into smaller methods.

Naming

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

Please read (and follow) the Java Naming Conventions.

This does not only apply to the casing of the identifiers.
It also applies to how names are "constructed".
E.g.: you named a method getAnagrams().
By conventions the prefix get is reserved for methods, that do not do any processing
but simply return a property of the object.
But your method does a lot more than that.
Therefore a better name could be findAnagramsOf(String word).

avoid single character names

Since the number of characters is quite limited in most languages you will soon run
out of names. This means that you either have to choose another character which is
not so obviously connected to the purpose of the variable. And/or you have to "reuse"
variable names in different contexts. Both makes your code hard to read and understand
for other persons. (Keep in mind that you are that other person yourself if you look
at your code in a few month!)

On the other hand in Java the length of identifier names is virtually unlimited.
There is no penalty in any way for long identifier names. So don't be stingy with
letters when choosing names.

Choose your names from the problem domain

Some of your identifiers (or at least parts of them) have technical meaning.
But your identifiers should convey you business solution.

example: characterCountMap,  c, sortString or arr.

Remember that the technical details may change while the meaning of your identifiers
in respect to the business problem will remain.
so this identifiers might better be:

characterCounts, currentCharacter, sortedCharacters or wordCharacters.


Generating permutations in OCaml open Core.Std;;

let print aofa =
    let s1 = ( Array.length aofa ) - 1 in
    for i = 0 to s1 do
        for j = 0 to (Array.length aofa.(i)) - 1 do
            printf "%d " aofa.(i).(j);
        done;
        printf "\n";
    done;
;;

let rec fact i =
    if i <= 1 then 1 else i * fact (i - 1)
;;

let rec permutations ints =
    let length = Array.length ints in

    if length < 2 then
        [|ints|]
    else begin
        let total = fact length in

        let result = Array.create total (Array.create length 0) in
        for i = 0 to total - 1 do
            result.(i) <- Array.create length 0
        done;

        let block_size = total / length in
        for i = 1 to length do
            let rest = Array.append (Array.sub ints 0 (i - 1)) (Array.sub ints i (length - i)) in
            let rights = permutations rest in
            for r = 0 to (Array.length rights) - 1 do
                let n = Array.append [|Array.get ints (i - 1) |] rights.(r) in
                result.((i - 1) * block_size + r) <- n
            done;
        done;

        result
    end
;;

let () =
    let aofa = permutations [|1; 2; 3|] in
    print aofa;
;;

And result:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

UPD:

As first step, I wrote naive implementaion on python and then make version in OCaml

def permutations(s):
    if len(s) > 1:
        for i, v in enumerate(s):
            for p in permutations(s[0: i] + s[i+1:]):
                yield [v] + p
    else:
        yield s

def main():
    for p in permutations([1, 2, 3]):
        print(p)

if __name__ == '__main__':
    main()

Your code is totally imperative. In some cases (probably in most) it's faster, but this not the best way to use OCaml :) Here is my solution in functional style:

Printing the list of lists can be done by iterating over list of lists:

let print lst =
  List.iter (fun l ->
      List.map string_of_int l
      |> String.concat " "
      |> print_endline
    ) lst

Next recursive function does:

Selects head element of the list and makes it heading element of the resulting list
Recursively calls itself on the list of all previous elements (minus resulting subset) + tail.

let rec permutations result other = function
  | [] -> [result]
  | hd :: tl ->
    let r = permutations (hd :: result) [] (other @ tl) in
    if tl <> [] then
      r @ permutations result (hd :: other) tl
    else
      r

All together. Initial result is empty and the stored list of previous elements is also empty:

let () =
  permutations [] [] [1; 2; 3]
  |> print


Presenting long string literals (URLs) in Python I have a web scraping application that contains long string literals for the URLs. What would be the best way to present them (keeping in mind that I would like to adhere to PEP-8.

URL = "https://www.targetwebsite.co.foo/bar-app/abc/hello/world/AndThen?whatever=123&this=456&theother=789&youget=the_idea"
br = mechanize.Browser()
br.open(URL)

I had thought to do this:

URL_BASE = "https://www.targetwebsite.co.foo/"
URL_SUFFIX = "bar-app/abc/hello/world/AndThen"
URL_ARGUMENTS = "?whatever=123&this=456&theother=789&youget=the_idea"
br = mechanize.Browser()
br.open(URL_BASE + URL_SUFFIX + URL_ARGUMENTS)

But there are many lines and it's not a standard way of representing a URL.

You could use continuation lines with \, but it messes the indentation:

URL = 'https://www.targetwebsite.co.foo/\
bar-app/abc/hello/world/AndThen\
?whatever=123&this=456&theother=789&youget=the_idea'

Or you could use the fact that string literals next to each other are automatically concatenated, in either of these two forms:

URL = ('https://www.targetwebsite.co.foo/'
       'bar-app/abc/hello/world/AndThen'
       '?whatever=123&this=456&theother=789&youget=the_idea')

URL = 'https://www.targetwebsite.co.foo/' \
      'bar-app/abc/hello/world/AndThen' \
      '?whatever=123&this=456&theother=789&youget=the_idea'

I often use the parenthesized version, but the backslashed one probably looks cleaner.


How to refactor this importer to handle validation errors? This is my importer to database from excel file. I would like to handle situations when any error raise. To not breaks whole import when one errors occurs.

For example when there is duplicated record and I have uniqueness validations. I would like to store this row id in errors table and inform about that at the end.

class DDImporter
  attr_accessor :file

  def initialize(path)
    @path = path
  end

  def open
    @file = Roo::Excelx.new(@path)
  end

  def sheets
    @file.sheets
  end

  def extract_sheets
    sheets.each do |sheet|
      unless sheet == ("risks" || "allergies_symptoms")
        extract sheet
      end
    end
  end

  def extract sheet_name
    @file.default_sheet = sheet_name

    header = file.row 1
    2.upto(file.last_row) do |i|
      row = Hash[[header, file.row(i)].transpose]
      # row.delete "id"
      object = sheet_name.classify.constantize
      object.create!(row)
    end
  end
end

It can be as simple as :

  def initialize(path)
    @path = path
    @imported = []
    @errors = []
  end

  def extract sheet_name
    @file.default_sheet = sheet_name

    header = file.row 1
    2.upto(file.last_row) do |i|
      row = Hash[[header, file.row(i)].transpose]
      # row.delete "id"
      model = sheet_name.classify.constantize

      # this is the part that gets the job done.
      object = model.new(row)
      if object.save
        @imported << object
      else
        @rejected << object
      end

    end
  end

... this way you can iterate through @imported or @rejected at the end of the import process (to display errors, or perform additional tasks).

This code can also easily be adapted to only catch exceptions :

  def extract sheet_name
    @file.default_sheet = sheet_name

    header = file.row 1
    2.upto(file.last_row) do |i|
      row = Hash[[header, file.row(i)].transpose]
      # row.delete "id"
      object = sheet_name.classify.constantize
      object.create!(row)
    end
  rescue ActiveRecord::RecordNotUnique, ActiveRecord::RecordInvalid => error
    # rejected record for these errors can be accessed with :
    error.record
    # to resume processing, just :
    error.continue
  end


Lispy code? Sum multiples of 3 or 5 up to 1000 I've started learning Lisp one more time (I seem to do this every couple years); my experience is with C, basically. I attempted to solve the Project Euler problem 1:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

My solution to the problem is below.
Please suggest improvements, style changes, indentation, commenting, naming of "objects", ...
(defun multiple-of-3-or-5p (n)
    "predicate for multiple of 3 or 5"
    (cond ((= 0 (rem n 3)) t)
          ((= 0 (rem n 5)) t)
          (t nil)))

(defun sum35 (n)
    "sum all multiples of 3 or 5 up to n (including n)"
    (cond ((= n 0) 0)
          (t (+ (if (multiple-of-3-or-5p n) n 0) (sum35 (- n 1))))))

;; in the repl use
;; (sum35 999)

(defun predicate-sum (predicate n)
    "sum integers up to n (including n) that match the predicate"
    (cond ((= n 0) 0)                                 ; stop recursion
          (t (+
              (if (funcall predicate n) n 0)          ; add n or 0 and
              (predicate-sum predicate (- n 1))))))   ; the recursed sum to (n - 1)

;; in the repl use
;; (predicate-sum 'multiple-of-3-or-5p 999)

Other than "stuff" relevant to the code above, I came across a few question while working on this problem.

What is the natural Lispy way to define upper boundaries? Include or exclude the specific value? Ie, if you see (summation 3 6) you think 3+4+5 or 3+4+5+6?
Is there a standard way to make a list of numbers 0 to 1000 (999)? Something like (make-list 0 1000)?

Thanks in advance

Conditions
In general something like "if a then true else false" can be simplified as "a". So your first function could be simplified as:
(defun multiple-of-3-or-5p (n)
  "predicate for multiple of 3 or 5"
  (or (= 0 (rem n 3)) (= 0 (rem n 5))))

Cond with only two cases
A cond with only two cases is written preferibly as an if. For instance:
(defun sum35 (n)
  "sum all multiples of 3 or 5 up to n (including n)"
  (if (= n 0)
      0
      (+ (if (multiple-of-3-or-5p n) n 0) (sum35 (- n 1)))))

Use the operators 1+ and 1- instead of adding or subtracting 1
The usual way of writing (- n 1) is (1- n).
Recursion and Iteration
Common Lisp has a very powerful iteration construct, loop (see for instance here for a detailed
discussion), that can make
simpler to write cases like in the last two functions. For instance:
(defun sum35 (n)
  "sum all multiples of 3 or 5 below n"
  (loop for i below n
        when (multiple-of-3-or-5p i) sum i))

; (sum35 1000)

Analogously,
(defun predicate-sum35 (predicate n)
  "sum integers up to n (including n) that match the predicate"
  (loop for i below n
        when (funcall predicate i) sum i))

; (predicate-sum35 #'multiple-of-3-or-5p 1000)

(note the use of #' to get a function).
Finally, to answer your last two questions:

The “natural” way in Common Lisp is to exclude the last value, as in all predefined functions that specify a range (for instance to get a substring with the first two characters of "foo", you can write (subseq "foo" 0 2), that returns "fo",
with the index starting from 0).

A primitive function does not exists. You can obtain a list of this kind very easily by using loop, for instance: (loop for i below 1000 collect i).

Edited
As suggested in a comment by @slepic, the algorithm is not the best one, since it checks for all the numbers from 0 to n, while one could simply sum directly all the multiples. Here is a possible solution:
(defun sum35 (n)
  (flet ((sum-m (k)
           (loop for i from k below n by k sum i)))
    (+ (sum-m 3) (sum-m 5) (- (sum-m 15)))))

Or you can use a direct formula, like that in another comment.


Iterate comparison - How can I write this better? I would like to write the following piece of code cleaner and more efficient, any comments will be greatly appreciated:

Dim dt As DataTable = SomeDataTable
    For Each dr As DataRow In dt.Rows
        Dim myColumn As String = dr("column").Trim().ToUpper()
        For Each group As String In collection
            If (group.Trim().ToUpper() = myColumn) Then
               'Add some logic here
            End If
        Next`

I'm not a VB.Net developer, but if I were writing this in C# I would use the Contains method on your collection. I'm assuming that your collection is a list of strings in this case.

I've included what the code might look like in VB.Net below. I give no guarantees that it works though. :)

Dim dt As DataTable = SomeDataTable

For Each dr As DataRow In dt.Rows
    Dim myColumn As String = dr("column").ToString().Trim()

    If collection.Contains(myColumn, StringComparer.OrdinalIgnoreCase) Then
        'Do your stuff here
    End If
Next


Does this work cross browser? Provided Object.prototype hasn't been modified, will the following snippet work in major browsers?

var obj = {length:0};
var push = Array.prototype.push;
push.call(obj,'1st value')
push.call(obj,'2nd value');

Many have responded that the above code is bad practice, but what makes code like this any better?

Array.prototype.slice(arguments,0)

Both are calling Array.prototypes on non Arrays.

I'm going to say no, because this is an array. It works, but you are hammering a screw at this point. Simply use an array.


Scraping thefreedictionary.com This scrapes results from thefreedictionary.com:

#!/usr/bin/python

from bs4 import BeautifulSoup as bs
import re
from requests import get

def remove_non_ascii(text):
    return re.sub(r'[^\x00-\x7F]+', '', text)

def get_soup(url):
    raw = remove_non_ascii(get(url).content)
    soup = bs(raw)
    return soup.select("#MainTxt")[0].select('.ds-single')[0].text.strip()

def lookup(word):
    base_url = "http://www.thefreedictionary.com/"
    query_url = (base_url + word)
    return get_soup(query_url)

if __name__ == '__main__':
    print lookup('linux')

Example

Warning: this script may fail to comply with thefreedictionary.com's TOS

According to PEP8, import re should come first
In free dictionary there is only one div having the class ds-single. You can simplify your code to search for this div
This doesn't apply to your program, but if you want to scrape multiple pages, it's better to use grequests.


Constructing and initializing global objects I have a script for a web page that has to initialize a lot of complex event handlers on page load. Because of the large number of events and DOM elements that these events should fire for, I want to construct a global object containing all the initialization logic.

var Global =
    {
        button1Handler: function () {
            return {
                button1: $("#button1"),
                init: function () {
                    this.button1.on("click", function () { alert("button1 clicked"); });
                }
            };
        },
        button2Handler: function () { /* */},
        init: function () {
            this.button1Handler().init();
            this.button2Handler().init();
            // ...
        }

    };

$(function () {
    Global.init();
});

But as I'm quite new to JavaScript, I have no idea whether this is the most simple or correct way to do this. And I'm not sure I like these chain function calls: button1Handler().init().

Is there a better way to write this piece of code?

First, I would suggest against the Global name. Too generic. Next, I would suggest against putting it in the global scope. You can put the declaration inside jQuery's ready handler.

Another thing is to avoid the unnecessary "configuration". Sometimes, it's best if the code is straight-forward. The structure of a configuration is sometimes a roadblock. Takes up too much syntax but doesn't immediately tell you what the code does.

For instance, if I was looking at this code for the very first time, I would be wondering how button1 is related to this.button1, what button1 should be, when is init is called, etc. Once I get the hang of it, sure it works. But what if there's an architectural change that invalidates this style of configuration? What if you've done this to 1000 things? You can't easily pull out and rewrite the code.

Keep it simple.

$(function () {

  $("#button1").on('click', handler);
  $("#button2").on('click', handler);

});

On the other hand, if you have an app that is already starting to look complex, consider using a simple framework. There's Ractive, Vue and Riot which are small frameworks allow you to write self-contained portions of the site. This way, each "component" only houses functionality of that component, splitting up this "large number" into sections.


Optimise Sieve of Eratosthenes I have written the following code for finding out the prime numbers less than or equal to n. When I enter the input n = 10^7, my program crashes. So I was wondering whether my code can be further optimised.

def sieve(n):
    array = []
    for i in range(1, n):
        array.append(True)
    for i in range(0, n-1):
        for j in range(2*i+4, n+1, i+2):
            if array[j-2] != False:
                if j % (i+2) == 0:
                    array[j-2] = False
    final = []
    for i in range(0, n-1):
        if array[i] == True:
            final.append(i+2)
    return final

First, I would clean up the indices in the inner loop. I think the +2 and -2 are a bit confusing at the first glance.

def sieve(n):
    array = []
    for i in range(0, n + 1):
        array.append(True)
    for i in range(2, n + 1):
        for j in range(2*i, n+1, i):
            if array[j] != False:
                if j % (i) == 0:
                    array[j] = False
    final = []
    for i in range(0, n+1):
        if array[i] == True:
            final.append(i)
    return final

This way, array indices directly correspond to their number, no conversion needed. This wastes array space for 0 and 1, but I think it is a lot easier to understand.

The primary optimization that is possible adjusts the ranges of the loops. Each non-prime
<= n
has a divisor <= sqrt(n) and thus we can limit the outer loop to range(2, math.sqrt(100) + 1)

Additionally we don't actually need to run the inner loop for numbers which are non-prime (since each non-prime has prime divisors) and we can add an if array[i] == True: to reduce the number of inner loops further.

The range of the inner loop can also be reduced. It actually can start at i^2 instead of 2*i since the argument made earlier also applies here. All non-primes smaller than i^2 must have an divisor < i and thus were already set to false in an earlier iteration of the outer loop.

If we apply these changes, we get the following code:

def faster_sieve(n):
    array = []
    for i in range(0, n + 1):
        array.append(True)

    for i in range(2, int(math.sqrt(n)) + 1):
        if array[i] == True:
            for j in range(i*i, n + 1, i):
                if array[j] != False:
                    if j % i == 0:
                        array[j] = False
    final = []
    for i in range(2, n + 1):
        if array[i] == True:
            final.append(i)
    return final

For comparison we can run

faster_sieve(int(math.pow(10, 7)))

and

sieve(int(math.pow(10, 7)))

On my machine:

~ time python faster_sieve.py
python faster_sieve.py  5.44s user 0.04s system 99% cpu 5.477 total

~ time python sieve.py
python sieve.py  32.97s user 0.03s system 99% cpu 33.003 total

Which is a lot faster!

Now we could to some python microoptimizations, but I don't know anything about python. A first step could be to replace the append-loop with something faster like array = [True] * (n + 1), which saves another second on my machine

~ time python faster_sieve.py
python faster_sieve.py  4.46s user 0.02s system 99% cpu 4.475 total

So, yes indeed, your code could be further optimized.

/e
I might add that there are already good reviews of python code for the sieve on this site. For example this which applies a lot of python optimization.

/e2

Looking at the code again and looking at Wikipedia, the checks inside the inner loop are actually not needed since j is per loop definition a multiple of i and we can simplify it to

for j in range(i*i, n + 1, i):
    array[j] = False

which optimizes the program further:

~ time python faster_sieve.py
python faster_sieve.py  2.61s user 0.01s system 99% cpu 2.617 total

/e3 After reading jerry's response and finding two bugs in his implementation, I think there is another easy optimization that can be added to his approach. Since i is always odd in his inner loop, so is i * i. Thus we can increase the increment step of the inner loop from i to i * 2 (i * i + i would be even). This result in the following results:

Simon: 3.5496606826782227
Jerry (broken): 1.7031567096710205
Josay: 2.2623558044433594
Krypton: 5.4344189167022705
Krypton2: 2.5819575786590576
Jerry2: 1.396036148071289

Krypton2 and Jerry2 being:

def krypton2(n):
    array = [True] * (n + 1)

    for i in range(2, int(math.sqrt(n)) + 1):
        if array[i] == True:
            for j in range(i*i, n + 1, i):
                array[j] = False
    final = []
    for i in range(2, n + 1):
        if array[i] == True:
            final.append(i)
    return final

def jerry2(n):
    array = [True] * n

    result = []

    result.append(2)
    for i in range(4, n, 2):
        array[i] = False;

    for i in range(3, int(math.sqrt(n) + 1), 2):
        if array[i]:
            for j in range (i*i, n, i * 2):
                array[j] = False;

    for i in range(3, n, 2):
        if array[i]:
            result.append(i)
    return result