As mentioned in a comment of mine, it's possible that there's a bug in the code. The OrderByDescending(p => p.UserLikes.Select(f => f.LikeStatus == LikeStatus.Like).Count() - p.UserLikes.Select(f => f.LikeStatus == LikeStatus.Dislike).Count()) call should always sort on a single value, 0. The call should be equal to OrderByDescending(p => p.UserLikes.Count() - p.UserLikes.Count()) because the Select method does not filter values.

That being said, I'll consider it as OrderByDescending(p => p.UserLikes.Where(f => f.LikeStatus == LikeStatus.Like).Count() - p.UserLikes.Where(f => f.LikeStatus == LikeStatus.Dislike).Count()) from here on out. If this is not the case let me know and I'll delete this answer.

I see that you count likes and dislikes a couple of times in your queries, in the OrderByDescending method and in the LikeCount and DislikeCount properties in the final Select. Keeping in mind this consideration I'd change the query in the following:

ret = _dbEntitySet.AsNoTracking()
       .Where(p => p.PostId == postId && p.IsPublished)
       .Include(p => p.UserLikes)
       .Select(p => new { DbEntity = p, LikeCount = p.UserLikes.Where(f => f.LikeStatus == LikeStatus.Like).Count(), DislikeCount = p.UserLikes.Where(f => f.LikeStatus == LikeStatus.Dislike).Count() })
       .OrderByDescending(p => p.LikeCount - p.DislikeCount)
       .Skip((reviewPageIndex - 1) * reviewPageSize)
       .Take(reviewPageSize)
       .Select(p => new PostModalReviewDisplay()
       {
           CommentCount = p.DbEntity.Comments.Count(),
           DislikeCount = p.DislikeCount,
           LikeCount = p.LikeCount,
           IsCurrentUserDisliked = p.DbEntity.UserLikes.Any(w => w.LikeStatus == LikeStatus.Dislike && w.UserInfoId == currUserId),
           IsCurrentUserLiked = p.DbEntity.UserLikes.Any(w => w.LikeStatus == LikeStatus.Like && w.UserInfoId == currUserId),

           Content = p.DbEntity.Content,
           Id = p.DbEntity.Id,
           UserInfo = new UserInfoExtraSmall()
           {
               AppUserId=p.DbEntity.UserInfo.AppUserId,
               Name=p.DbEntity.UserInfo.Name,
               Surname=p.DbEntity.UserInfo.Surname,
               ProfileImage=p.DbEntity.UserInfo.ProfilePicture.SmallPath
           }
       })

One more thing that comes to mind is to switch the comparison clauses in the IsCurrentUserDisliked and IsCurrentUserLiked properties. Note that the two versions could be the same in terms of performance, depending on the execution plan that the query optimizer generates, but personally I prefer to put the most selective comparison clause first.

So, the final version would be the following:

ret = _dbEntitySet.AsNoTracking()
       .Where(p => p.PostId == postId && p.IsPublished)
       .Include(p => p.UserLikes)
       .Select(p => new { DbEntity = p, LikeCount = p.UserLikes.Where(f => f.LikeStatus == LikeStatus.Like).Count(), DislikeCount = p.UserLikes.Where(f => f.LikeStatus == LikeStatus.Dislike).Count() })
       .OrderByDescending(p => p.LikeCount - p.DislikeCount)
       .Skip((reviewPageIndex - 1) * reviewPageSize)
       .Take(reviewPageSize)
       .Select(p => new PostModalReviewDisplay()
       {
           CommentCount = p.DbEntity.Comments.Count(),
           DislikeCount = p.DislikeCount,
           LikeCount = p.LikeCount,
           IsCurrentUserDisliked = p.DbEntity.UserLikes.Any(w => w.UserInfoId == currUserId && w.LikeStatus == LikeStatus.Dislike),
           IsCurrentUserLiked = p.DbEntity.UserLikes.Any(w => w.UserInfoId == currUserId && w.LikeStatus == LikeStatus.Like),

           Content = p.DbEntity.Content,
           Id = p.DbEntity.Id,
           UserInfo = new UserInfoExtraSmall()
           {
               AppUserId=p.DbEntity.UserInfo.AppUserId,
               Name=p.DbEntity.UserInfo.Name,
               Surname=p.DbEntity.UserInfo.Surname,
               ProfileImage=p.DbEntity.UserInfo.ProfilePicture.SmallPath
           }
       })

As a final thought, I agree with @AdrianoRepetti's comment:

  Nothing better than to check generated SQL then they query plan and then measure...

Check the generated query plan for different versions and use the query that best suits your needs.


My advice is to not mess about with something that's been well and truly tested :-)

No, not really: if you find an algorithm that's better then, by all means, use it. However, in this case, for general data, this isn't going to be an improvement.

The power of binary search, and other O(log N) type algorithms, lies in the fact that you dispose of half the remaining search space with each iteration. In other words, if the initial search space (array size) was 1000, the first iteration removes 500 of them.

Any change to the "midpoint" (the divider between what you're keeping in the search space and what you're disposing of) that you select during an iteration has the potential to improve or degrade the performance. For example, putting the midpoint at 25% has the potential to reduce the search space even faster (if you're right) or slower (if you're wrong).

Now, if you know of some property of the data, you can use that to your advantage to improve an algorithm. In fact, it's the "extra" knowledge about your list (the fact that it's sorted) that allows you to optimise what would normally be a sequential search into a binary one.

So it all comes down to how good your extra information is. In this case, the values of the two end nodes alone are not really indicative of where the midpoint should be. You only have to look at the list:

[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 500, 1000]

to see this in action.

If you were looking for 500 in that list, you might decide that, based on the first and last elements being 1 and 1000, it would be in the middle somewhere, which is clearly not the case.

Similarly, if you were looking for 14, you might first check elements around the 1.4% mark (14/1000) which would probably be the first element, despite the fact it's right up at the other end.

Of course, that's not to say that other extra information would not help. If you knew that the data was fairly evenly distributed over the range, then your improvement may be worth it.

You also need to be aware that it's usually only going to be important with large data inputs, so it may not necessarily be worth it even if it turns out to be much better. Even bubble sort is blindingly fast for 100 elements :-)


How about:

accepted_truthy_characters = {'y', 't'}

def truthy(value):
    if isinstance(value, basestring):
        return value and value[0].lower() in accepted_truthy_characters
    return bool(value)

In Python 3.x, basestring won't work and you'll need isinstance(value, str) instead.

One thing you missed is that value might be a string, but it might be empty, which would leave you with an IndexError.

Python's bool() will check an int for you, so I don't think you need to check if it's a Number, convert it with int(), and then bool(), unless I'm missing something about your use case.

Out of curiosity, why do you need this? Are you checking user input? Won't that always be a string anyway? And in that case, wouldn't it be better to just check a few allowed "positive" strings?


ELisp function to allow file renaming in Emacs

Judgment circuits deactivated; you have nothing to fear.

I was going to suggest that there must already be a function that you can call to force uniquify a buffer, but M-x apropos RET ^uniq doesn't show any documented functions that would do that for you (take a look and try a few out if you like, you may find a more elegant solution).

Lisp (actually, Elisp and Common Lisp; Scheme does its own thing) convention is to end predicate functions with -p or p rather than begin them with is-.

(defun unique-name-for-buffer-p (new-name)
  (let ((file-name (buffer-file-name))
        (dir-name (file-name-directory buffer-file-name)))
    (let ((new-complete-name (concat dir-name new-name)))
      (progn (not (string-equal file-name new-complete-name))))))

Your predicate seems to be nesting lets only because you need new-complete-name to refer to dir-name. When you're in a situation like that, you can instead use let*. It's the same as let except that its clauses are guaranteed to be evaluated in order (it's still good style to use let when you can, but one let* is better than many nested lets).

(let* ((file-name (buffer-file-name))
       (dir-name (file-name-directory buffer-file-name))
       (new-complete-name (concat dir-name new-name)))
    (progn (not (string-equal file-name new-complete-name))))

You only need explicit progn when you want to evaluate multiple expressions as one (you use it correctly in your nested ifs, but read on).

(defun unique-name-for-buffer-p (new-name)
  (let* ((file-name (buffer-file-name))
         (dir-name (file-name-directory buffer-file-name))
         (new-complete-name (concat dir-name new-name)))
    (not (string-equal file-name new-complete-name))))

The nested ifs in your second function can be expressed as a single cond (which also gets rid of that otherwise legitimate progn).

(defun rename-file-and-buffer (new-name)
  "Renames both current buffer and file it's visiting to NEW-NAME."
  (interactive "sNew name: ")
  (let ((name (buffer-name))
        (filename (buffer-file-name))
        (dir-name (file-name-directory (buffer-file-name))))
     (cond ((not filename)
            (message "Buffer '%s' is not visiting a file!" name))
           ((not (unique-name-for-buffer-p new-name))
            (message "A buffer named '%s' already exists in that location!" new-name))
           (t (rename-file (file-name-nondirectory filename) new-name 1)
              (kill-buffer)
              (set-buffer (find-file (concat dir-name new-name)))))))


Gson to Model containing several return types for one key

Iterating through an entrySet()

If what you really want is to put all the JSON objects into a success map, rather than overwriting each of them with every iteration, there's a way to stream it:

Map<String, Object> map = object.entrySet().stream()
                                .collect(Collectors.toMap(Entry::getKey,
                                            entry -> (Object) entry.getValue()));
result.setSuccess(map);

In any case, a more fluent implementation of HashMap<>() {{ ... }} is to use Collections.singletonMap():

object.entrySet().forEach(entry -> {
    Map<String, Object> map = Collections.singletonMap(entry.getKey(), entry.getValue());
    // ...
});

Modeling

You can consider have a more domain-based modeling of the successful results, instead of a simple Map<String, Object> in your HueResponse. For example, consider a Group of Action objects that have a state consisting of enabled (aka on), effect and hue? That seems to adhere closer to the results, giving you a more meaningful application.


Trie with insert, search, and startsWith methods for lowercase strings

Assuming the next attribute of TrieNode is just a lookup for letters of the alphabet, you might be better off replacing it with a dictionary that maps letters of the alphabet to their next value. Something like:

class TrieNode(object):
    def __init__(self):
        self.next = {letter: ['!', None] for letter in string.ascii_lowercase}
        self.isWord = False

and now, rather than mucking around with ord() in your insert() and search() methods, you can use the characters directly. That won’t fundamentally change the complexity, but will make a small performance saving.

I think insert and search of a trie is O(key_length), so this is probably the sort of saving you need. You can’t change the complexity.

A few other small suggestions:

Comparisons to None should use foo is None and foo is not None, not direct equality.
Once you’re using the characters as keys in the next attribute, you’d be better of replacing those while i < wordLength loops with something like for i, char in enumerate(word).
In general, PEP 8 convention is that Python variables are lowercase with underscores (e.g. is_word, starts_with), and only classes are camel case. (Although as @Graipher notes in the comments, camel case is specified for startsWith().)


One important thing to mention - if you're cythoning a for loop through a range, you need to cdef the type of the index.

def pointless_add_slow(j):
     for i in range(120000):
           i = i+j
     return i

%timeit pointless_add_slow(1)
100 loops, best of 3: 3.71 ms per loop

New block in jupyter:

%%cython
def pointless_add(j):
     cdef int i
     for i in range(120000):
           i = i+j
     return i

%timeit pointless_add(1)
100 loops, best of 3: 1.98 ms per loop


Perform SELECT INTO Statement and add Primary Key afterwards

Your current code effectively writes the table twice.

Once as a heap and then again as a clustered index (with an intermediate sort step) after you add the primary key.

I'd just create the table upfront with the desired primary key and insert into it.

USE DBApps_Pulse_WarehouseAreas;

CREATE TABLE [dbo].[Tbl_Partmaster]
  (
     Code        VARCHAR(10) NOT NULL CONSTRAINT PK_Tbl_Partmaster PRIMARY KEY,
     Description NVARCHAR(500) NOT NULL
  );

INSERT INTO [dbo].[Tbl_Partmaster]  WITH (TABLOCKX)
SELECT Code,
       Description
FROM   SYSDataBridge.dbo.View_Pulse_Partmaster_Synchronized;

For at least three versions of SQL Server an insert into an empty B tree has been able to be minimally logged.

In order to avoid page splits there might be a sort operator in the execution plan if the estimated number of rows is sufficiently high (or if the source has an index that could potentially present the selected columns in order of code this direct insert might avoid the need to sort all together).

Finally avoid Hungarian notation such as Tbl_. At best it adds nothing but clutter. At worst at some point you might want to refactor the database and transparently replace the table with a view without updating calling code. Then the Tbl_ prefix would be down right misleading.


Handling various types of nodes when traversing a DOM tree

Consider creating an object which can handle each case:

interface NodeHandler {
    void handle(Node node, Element current, ...);
}

class ElementHandler implements NodeHandler {
    public void handle(Node node, Element current, ...) {
        readElement(node, current);
    }
}

You can then populate a map, like this, to look up the appropriate handler for a node:

private static Map<Integer, NodeHandler> handlerMap;
static {
    handlerMap = new HashMap<Integer, NodeHandler>();
    handlerMap.put(Node.ELEMENT_NODE, new ElementHandler());
    //...
}

and then...

handlerMap.get(node.getNodeType()).handle(...);

I don't think this makes the code shorter, but it does make the code more maintainable. Each object has a single, clear responsibility, and you don't have to deal with issues like fall-through cases, or state getting mingled between different handlers. You could conceivably invent new handlers without actually changing the implementation of the readTree() method, or impacting the behavior of existing handlers.


Is this FizzBuzz Swift-y?

Kinda, but it could be a lot better.  Here's what I would do to fix it:

Extrapolate this code into a method, then call the method from the for loop.

func fizzbuzz(i: Int) -> String
{
   // ...
}

There is a handy Swift feature called "Tuples". Tuples are groupings of values.   We can use them to represent our results from the modulo operation.

let result = (i % 3, i % 5)

Now that we are using a Tuple to represent the result, we can easily use a switch to perform the necessary actions.

switch result
{
    case (0, 0):
        return "FizzBuzz"
    case (0, _):
        return "Fizz"
    case (_, 0):
        return "Buzz"
    default:
        return "\(i)"
}

You might be wondering what that underscore is.  That _ is used to indicate a discarded value that we don't really care about, the value in the tuple that doesn't really matter to us in the evaluation.
Your for loop isn't very "Swift-y".  Here's how I would write is so that it calls the function 100 times.

for number in 1...100
{
    println(fizzbuzz(number))
}

Answers to your questions

  The parenthesis in if statements are optional in Swift. Should that be
  a thing, or should we stick with them?

This is a very style-oriented question.  Style differs from person to person, and is very organic.  Since no "style rules" have been put in place, do whatever you are most comfortable with.

  The curly-braces were optional in Objective-C (and lots of programming
  languages) but they're not in Swift.

This was implemented in order to prevent simplified if conditional statements and the class of bugs that associated with them.  For example:

if (someCondition)
    doThisForSomeCondition()
    doThisAsWell()
if (someOtherCondition)
// ...

Swift's forced usage of braces eliminated the execution of doThisAsWell() outside of the someCondition conditional statement.

  Is it okay to let the type be implicitly determined, or should we
  stick with explicitly declaring the type?

Whether or not you include the explicit type is a matter of taste. In some contexts it might make your code more readable.  However, this is usually not the case; and since the compiler will almost never assign the wrong type to your variable, I usually leave the type to be implicitly determined.  Whatever way you decide will not affect speed/efficiency of the code, so that is not a factor.


You are doing double force-unwraps, twice. This is really just asking for trouble

As others have pointed out in their comments, there are a few edge cases you should guard against. Good thing is you can do both at the same time.

Additionally, you should avoid using shortened names for your variables. In Swift, we usually type everything out.

I've updated and annotated your code below, take a look;

@IBAction func clickHereButton(_ sender: UIButton) {

    // Start by ensuring we have actual values entered by the user
    guard let name = nameText.text,
          let sizeString = sizeText.text,
          let weightString = weightText.text else {
        return
    }

    // Then, ensure the values are valid Doubles
    guard let size = Double(sizeString),
          let weight = Double(weightString) else {
        return
    }

    // Finally, ensure that size > 0
    guard size > 0 else {
        return
    }

    // We now are 100% safe and can start calculating our BMI
    let bmi = weight / pow(size, 2)
    let bmiRounded = (round(bmi * 10) / 10)

    // Even though this var name is longer, it's clearer what it is.
    let alertViewController = UIAlertController(title: "BMI for \(name)", message: "Your Body-Mass-Index is \(bmiRounded)", preferredStyle: .alert)

    // You can use the `.init(_:)` shorthand when a specific type is required
    alertViewController.addAction(.init(title: "Okay", style: .default))
    self.present(alertViewController, animated: true, completion: nil)
}

The only other thing I would improve is to move your actual BMI calculations to a specific function that takes in the size and weight parameters.

For the rest, it's pretty much all good.


"Acro Words" - Creating Acronyms of a Text that are Words

1. Review

The lines are quite long, which means that it doesn't fit in the box here at Code Review. The Python style guide (PEP8) recommends sticking to 79 characters.
There are no docstrings. What do all these functions do? What am I supposed to pass as parameters?
Instead of:

[x for x in expression]

write:

list(expression)

and instead of:

{x for x in expression}

write:

set(expression)

This simplifies powerset to:

def powerset(seq):
    """Return a set whose elements are tuples of elements of seq."""
    return set(chain.from_iterable(combinations(seq, r)
                                   for r in range(len(seq) + 1)))

Instead of building a list:

return all([y in dictionary for y in in_string])

you can often just pass a generator expression to a function:

return all(y in dictionary for y in in_string)

This avoids constructing an intermediate list in memory.
Similarly, instead of:

tuple([''.join(x) for x in slices(data, indices)])

write:

tuple(map(''.join, slices(data, indices)))

In slices, I think it would be clearer to use tuple unpacking to give names to the elements of y, and so avoid the mysterious *list(y). Also, since the chains are the same length, you can use zip instead of zip_longest:

return [list(islice(data, start, stop)]
        for start, stop in zip(chain([0], indices),
                               chain(indices, [len(data)]))]

Consider using the pairwise recipe from the itertools documentation, and writing:

indices = chain([0], indices, [len(data)])
return [list(islice(data, start, stop)]
        for start, stop in pairwise(indices)]

The expression line.rstrip('\n') is repeated in get_dictionary.

2. Algorithm

The approach taken here is known as generate-and-test. The code generates all subsequences of the input, and then all ways to split the subsequences into words, and then tests whether each set of words is valid. The problem with this approach is that it takes time that's exponential in the length of the input.

What you need is some way to prune the search so that most of the exponentially many candidates subsequences are never considered (because they don't appear in your dictionary).

I'll sketch an algorithm. Take your dictionary:

BLACK
BLUE
BLUER
GREEN
GREY

and transform it into a prefix tree (in the diagram, nodes with a thicker border indicate ends of valid words in the dictionary):

We'll carry out a depth-first search over all the possible substrings of the input, but at each branch of the search in the word we'll also have a corresponding position in the prefix tree. At each step of the search we can either add the first letter of the input to the candidate subsequence and move downwards in the prefix tree, or discard the first letter of the input and remain at the same point in the prefix tree. This gives us two possible branches in the search.

Now suppose the input is the word ABSOLUTE. We start the search with input ABSOLUTE, an empty candidate subsequence, and the position at the root of the prefix tree:

Can we take the first branch of the search (adding the A to the candidate subsequence and moving down in the prefix tree)? No, because we can't move down in the prefix tree from our current position to an A. So this branch of the search goes nowhere.

In the other branch of the search (where we discard the A), we now have input BSOLUTE (with candidate subsequence and position in the prefix tree unchanged).

From this position, we can take the first branch, because there is a transition to B in the prefix tree, so we can add B to the candidate subsequence, discard the B from the input, and continue to here in the search:

And so on. You'll see that in this algorithm we immediately prune any step in the search that we know can never lead to a valid subsequence.


Make a git repository read-only over ssh depending on the key used

Should be

printf "%s\n" "$2" | grep -E "^git-upload-pack" && sh -c "$2"

Notes:

sh not bash for portability
The printf instead of echo is for safety.  What happens if someone puts  "-n foo" as "$2"?


String building in code is typically messy, especially without a native String.Format() or sprintf()  in Javascript. Building HTML is the worst offender, too.

Other than using a templating engine, like ICanHaz.js (which this use case alone doesn't really justify), you could also build a helper function for creating option tags.

function buildOption(value, isSelected) {
    return "<option value='"+value+"' "+(isSelected ? "selected" : "")+">"+value+"</option>";
}

If you're building a lot of these drop-down options, it might makes things more readable:

for (var i = 0; i < 12; i++) {
    var option = buildOption(i + year, i === 0);
    $('.card-expiry-year').append(option);
}

It's a good idea to avoid long lines/sections of code which have a simple purpose, but have to be read carefully to understand what they do (complicated regular expressions are a good example).

Extracting that functionality into a function avoids this, because the function signature is all someone would need to read to understand what it does.


Your code is SSE but not AVX, so here is the SSE version to generate the mask. The second part is same as yours. I modified it from my other code and NEVER tested:

; generate the bit mask
pcmpeqd         xmm15, xmm15  ; FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF
psrlq           xmm15, 63     ; 00000000 00000001 00000000 00000001
movdqa          xmm14, xmm15  ;
psllq           xmm14, 17     ; 00000000 00020000 00000000 00020000
por             xmm15, xmm14  ; 00000000 00020001 00000000 00020001
movdqa          xmm14, xmm15
psllq           xmm14, 34     ; 00080004 00000000 00080004 00000000
por             xmm15, xmm14  ; 00080004 00020001 00080004 00020001
movdqa          xmm14, xmm15
psllq           xmm14, 4      ; 00800040 00200010 00800040 00200010
punpcklqdq      xmm15, xmm14  ; 00800040 00200010 00080004 00020001

; generate the second bit mask
movdqa          xmm15, xmm14
psllw           xmm15, 8      ; 80004000 20001000 08000400 02000100

; load and broadcast DX
movd            xmm0, edx     ; xmm0 = sliver
pshuflw         xmm0, xmm0, 0 ; xmm0 = sliver * 4
pshufd          xmm0, xmm0, 0 ; xmm0 = sliver * 8
movdqa          xmm1, xmm0

; apply the mask
pand            xmm0, xmm14   ; apply mask
pand            xmm1, xmm15   ; apply mask
pcmpeqw         xmm0,xmm14    ; mask to FFFF
pcmpeqw         xmm1,xmm15    ; mask to FFFF

If you are using AVX, you can omit those movdqa and the code will look better. The SSE version is long and I am not sure its better than a simple memory read, as your did.


I've splitted this class into multiple pieces and added a new feature that now allows me to insert NULL into nullable columns.

It starts with the LoggingConfigurationExtensions to get the DatabaseTargets

public static class LoggingConfigurationExtensions
{
    public static IEnumerable<DatabaseTarget> DatabaseTargets(
        this LoggingConfiguration loggingConfiguration,
        Func<DatabaseTarget, bool> predicate
    )
    {
        return loggingConfiguration.AllTargets.OfType<DatabaseTarget>().Where(predicate);
    }
}

The query generation logic now belongs to the DatabaseTargetQueryGenerator

public static class DatabaseTargetQueryGenerator
{
    public static void GenerateInsertQueries()
    {
        // The commandText attribute must conatain at least the table name.
        // Each identifier must be enclosed in square brackets: [schemaName].[tableName].

        // https://msdn.microsoft.com/en-us/library/ms175874.aspx?f=255&MSPPError=-2147217396
        // https://regex101.com/r/19GjqR/1
        // h t t ps://regex101.com/delete/QObrsCHVjaX8gGCysAn6yApJ

        var tableNameMatcher = new Regex(@"^(\[(?<schemaName>[a-z_][a-z0-9_@$#]*)\].)?\[(?<tableName>[a-z_][a-z0-9_@$#]*)\]$");

        var databaseTargets = LogManager.Configuration.DatabaseTargets(databaseTarget => tableNameMatcher.IsMatch(databaseTarget.CommandText()));
        foreach (var databaseTarget in databaseTargets)
        {
            databaseTarget.CommandText = databaseTarget.GenerateInsertQuery();
        }
    }

    private static string GenerateInsertQuery(this DatabaseTarget databaseTarget)
    {
        const string insertQueryTemplate = "INSERT INTO {0}({1}) VALUES({2})";

        return string.Format(
            insertQueryTemplate,
            databaseTarget.CommandText(),
            string.Join(", ", databaseTarget.Parameters.Select(x => x.Name())),
            string.Join(", ", databaseTarget.Parameters.Select(x =>
            {
                var sql =
                    x.Nullable()
                        ? string.Format("NULLIF({0}, '')", x.FullName())
                        : x.FullName();

                // Rename the SqlParameter because otherwise SqlCommand will complain about it.
                x.Name = x.FullName();

                return sql;
            })));
    }
}

another small piece helps me to get the actual commandText

public static class DatabaseTargetExtensions
{
    public static string CommandText(this DatabaseTarget databaseTarget)
    {
        return ((SimpleLayout)databaseTarget.CommandText).OriginalText;
    }
}

these extensions encapsulate the parameter name:

public static class DatabaseParameterInfoExtensions
{
    // https://regex101.com/r/wgoA3q/1
    // h t t ps://regex101.com/delete/BDmR7fAqwYQiT5DW5PKAJFAm

    private static readonly Regex ParamRegex = new Regex("^(?<prefix>.)(?<name>[a-z0-9_-]+)(?:[:](?<null>null))?", RegexOptions.IgnoreCase);

    public static string Prefix(this DatabaseParameterInfo parameter)
    {
        return ParamRegex.Match(parameter.Name).Groups["prefix"].Value;
    }

    public static string Name(this DatabaseParameterInfo parameter)
    {
        return ParamRegex.Match(parameter.Name).Groups["name"].Value;
    }

    public static string FullName(this DatabaseParameterInfo parameter)
    {
        return string.Format("{0}{1}", parameter.Prefix(), parameter.Name());
    }

    public static bool Nullable(this DatabaseParameterInfo parameter)
    {
        return ParamRegex.Match(parameter.Name).Groups["null"].Success;
    }
}

this means I can now create a config like this one

<target xsi:type="Database" name="Log" commandText="[dbo].[Log]" dbProvider="System.Data.SqlClient" connectionString="..">
  <parameter name="@Timestamp" layout="${longdate:universalTime=true}" />
  <parameter name="@LogLevel" layout="${level:uppercase=true}" />
  <parameter name="@Logger" layout="${logger}" />
  <parameter name="@Message" layout="${message}" />
  <parameter name="@Exception:null" layout="${onexception:${exceptionLayout}}" />
</target>

where

commandText="[dbo].[Log] specify the [Schema].[Table] to generate the INSERT for
@Exception:null means it is nullable column


Finding the maximum distance from the starting node

The code does not work because of a typo — there is a call to distance_sites but there is no such function.
There are no docstrings. What do these functions do? How do I call them?
In order to improve the performance, we need to measure it, and in order to do that, it's helpful to be able to make test cases of arbitrary sizes. So let's write a test case generator:

from itertools import product

def test_case(n):
    """Construct a graph with n**2 nodes and O(n**2) triangles, and return
    a tuple (graph, capital, number of nodes).

    """
    graph = defaultdict(list)
    for i, j in product(range(n), repeat=2):
        k = i * n + j
        if i < n - 1:
            graph[k].append(k + n)
            graph[k + n].append(k)
        if j < n - 1:
            graph[k].append(k + 1)
            graph[k + 1].append(k)
        if i < n - 1 and j < n - 1:
            graph[k].append(k + n + 1)
            graph[k + n + 1].append(k)
    return graph, 0, n * n

Then we can easily measure the performance of the code using timeit.timeit:

>>> from timeit import timeit
>>> timeit(lambda:distant_sites(*test_case(50)), number=1)
51.7171316598542

with \$n=50\$ the graph has 2,500 nodes and 4,802 triangles.
queue.Queue is a thread-safe data structure intended for use by multi-threaded programs. It has to take and release a lock for every operation, so it is overkill to use this in a single-threaded program. It is more than ten times faster to use collections.deque instead:

>>> timeit(lambda:distant_sites(*test_case(50)), number=1)
4.451224883086979

The code computes the distance from the capital to each town by running a separate breadth-first search for each town. But this repeats a lot of work: in the course of finding the distance to town A, the breadth-first search will have to visit towns B, C, D, and so on. It would make sense to remember the distance to each town as we visit it, and so compute the distances from the capital to all the towns in one go:

from collections import deque

def distances(graph, origin):
    """Return a dictionary mapping each node in graph to its distance from
    the origin.

    """
    result = {origin: 0}
    visited = set([origin])
    queue = deque([origin])
    while queue:
        node = queue.popleft()
        distance = result[node] + 1
        for neighbour in graph[node]:
            if neighbour not in visited:
                result[neighbour] = distance
                visited.add(neighbour)
                queue.append(neighbour)
    return result

This gives a couple of orders of magnitude speedup on the test case:

>>> timeit(lambda:distant_sites(*test_case(50)), number=1)
0.030185375828295946

The code for finding the most distant sites looks at all triangles. But this likely involves a lot of wasted effort. For example, suppose we find a triangle whose nodes have distance 48, 49 and 50 from the origin (with sum 147). Now there is no need to look at any triangle unless it contains a node with distance \${147\over 3} = 49\$ or more. So if we sort the nodes in reverse order by their distance from the origin and just remember the best-scoring site, then we may not have to consider very many sites before we know that we have found the most distant one.

def distant_sites(graph, origin):
    """Return the pair (max_site_dist, site_count), where max_site_dist is
    the maximum distance of any site in the graph from the origin, and
    site_count is the number of sites at that distance. A "site" is a
    triangle of nodes, and its distance from the origin is the sum of
    the distances of the three nodes.

    """
    distance = distances(graph, origin)
    nodes = sorted(((d, n) for n, d in distance.items()), reverse=True)
    max_site_dist = 0
    site_count = 0
    for dist1, node1 in nodes:
        if dist1 * 3 < max_site_dist:
            break
        neighbours = graph[node1]
        for node2 in neighbours:
            dist2 = distance[node2]
            if (dist2, node2) >= (dist1, node1):
                continue
            for node3 in graph[node2]:
                if node3 not in neighbours:
                    continue
                dist3 = distance[node3]
                if (dist3, node3) >= (dist2, node2):
                    continue
                site_dist = dist1 + dist2 + dist3
                if site_dist > max_site_dist:
                    max_site_dist = site_dist
                    site_count = 1
                elif site_dist == max_site_dist:
                    site_count += 1
    return max_site_dist, site_count

The speedup you get from this optimization depends on the kinds of graph you feed it (if there are few sites then it won't make much difference). For my test case we get about 40% speedup:

>>> timeit(lambda:distant_sites(*test_case(50)), number=1)
0.017997111193835735


'/ Data Structure: "Company Numbers", once input, will be stored as strings
'/ Company Number: 8-character string, generally 8-digits but sometimes with text prefixes E.G. "OC374102"

'/ Folder Path for monthly CH downloads: "S:\Investments\Data\Companies House\Monthly Companies House Downloads\"
'/ Filename Strucutre of a Monthly Folder: [parentFolderPath]"Accounts_Monthly_Data-"[Full Month Name][yyyy]"\" - Square Brackets not in filename
'/ Filename Structure of an individual filing: [Monthly Folder Path]"Prod224_0005_"[8-character Company Registration Number]"_"[yyyymmdd][.html OR .xml] - Square Brackets not in filename

I don't see the need for the / slash here. The VBE renders comments in a very distinctive green color: really, you couldn't miss a comment block if you tried:

Why fully qualify Scripting.Dictionary, but not Excel.Range?
Seriously, your code isn't bad at all.
Except I'm not sure I understand the need for AssignArrayBounds, and LB1/UB1 are awful names, as much as ix would be better off as either i or index.

This part can be simplified:

If IsNumeric(trimText) Then
    companyNumber = Right("00000000" & trimText, 8) '/ Add back any leading zeroes that Excel may have stripped

If trimText is numeric, then you can use the Format function to perform the padding:
If IsNumeric(trimText) Then
    companyNumber = Format(trimText, "00000000")

Simple as that!
I'd do away with multiple declarations in a single instruction:

Dim textValue As String, trimText As String
Dim companyNumber As String

textValue = CStr(vValue)
trimText = Trim(textValue)

...and move everything closer to their first usage:
Dim textValue As String
textValue = CStr(vValue)

Dim trimText As String
trimText = Trim$(textValue)

Dim result As String ' clearly the local I'm returning

Notice Trim$ here. Under the hood, Trim$ is really calling the VBA.Strings._B_str_Trim function; on the other hand, Trim is calling the VBA.Strings._B_var_Trim function. One returns a String, the other returns a Variant. By using the Variant variant, you're forcing an implicit conversion to a String, implicit conversion that can completely be avoided by calling the String-returning function in the first place.
The same applies to Right/Right$, respectively VBA.Strings._B_var_Right and VBA.Strings._B_str_Right. Rubberduck's inspections wiki will be updated for the 2.0 release with a full list of all these not-quite-string functions.


Since you are making calls to math.random a lot, keep a local copy in your code:

local random = math.random

Why are you switching between io.write and print statements? Use a string.format to format the data as you want:

print( ("You dealt %d damage!"):format(attackdamage) )

The above is merely a representation. It can be made a lot better (by putting templates as variables etc.)

n = math.random(10) + 1

The above will generate n in the range of 2 to 11. From the docs:

  When called with two integers m and n, math.random returns a
  pseudo-random integer with uniform distribution in the range [m,n].
  [...] The call math.random(n) is equivalent to math.random(1,n).

And, no need for keeping a temporary variable (here n):

enemyhp = 10 * random(10) -- better yet, use random(10, 100)

escapechance = math.random(2)
if escapechance == 1 then
escape = true
end

can simply become:

escape = random(2) == 1

Convert your input to lowercase first. Players might enter Attack or ATTACK too.

if input:lower() == "attack"

or

local input = io.read():lower()

Most important

You should encapsulate your player, enemies etc. inside objects. Lua supports a rough implementation of OOP design using tables. Read the Lua PiL chapter #16


Self-hosting WCF in Windows Forms without another Windows process

You can also start host in another thread:

Task.Factory.StartNew(() =>
    {
            ServiceHost host = new ServiceHost(typeof(MyService));
            host.Open();
    };

(or using classic Thread and ThreadStart).


find the longest sequence of consecutive numbers in decreasing order

The problem with the algorithm is:
1. there is no logic that recognizes the ending of the on-going consecutive decreasing sequence.
2. there is no logic that compares candidate sequences and tracks the longer one.

If we walk through the code, we can see it encounters a sequence of 4,3,2 starting from 4th iteration and then it encounters a sequence of 100,99,98,97. So the output is expected.

An example of working code:

arr=[5,2,7,4,3,2,0,8, 9,100,99,98,97,93,92]
longest = []
current = []
i = 0
if len(arr < 2):
    print(arr)
    return

while i < len(arr)-1:
   current.append(arr[i])
   j = i + 1
   while j < len(arr) and arr[i] == arr[j] + j-i:
      current.append(arr[j])
      j += 1

   i = j # start a new sequence at index j

   if len(current) > len(longest):
       longest = current
   current = []

print(longest)

There are definitely better ways to implement this in idiomatic python but hopefully, the code above illustrates the algorithm.


20+ percent faster using the stack for the extra buffer.

Matrix     Question     Answer(1)    Faster
-------------------------------------------
16 x 16    3.62 µsec    2.62 µsec    27.6 %
13 x 13    2.67 µsec    2.05 µsec    23.2 %
10 x 10    1.77 µsec    1.35 µsec    23.7 %
 7 x  7    1.02 µsec    0.77 µsec    24.5 %
 4 x  4    0.56 µsec    0.44 µsec    21.4 %

Setting up a temporary scratch buffer in the stack proved to be a winner. A decent speed increase, no need for the 3rd parameter, and with a single branch target, applying code alignment could be a bit easier.

This pushes the same 5 registers but delays assigning EBP so it can be used as an EndOfBuffer marker. A minor drawback is that the easy recognizable  EBP-offsets for the parameters (+8, +12, ...) are gone. Requires some more attention to detail like in the ESP-offsets of today.

Nothing is pushed on the stack below the local stack buffer and so keeping ESP dword-aligned is not needed.

This is cleaner code. I think addressing the parameters several times over, looked a bit untidy.

; TransposeSquareMatrix(Address, Rank)
A1: push    ecx edx esi edi ebp
    mov     ebp, esp
    mov     esi, [ebp+24]   ; Address
    mov     edx, [ebp+28]   ; Rank
    mov     ecx, edx
    imul    ecx, ecx        ; -> Size of matrix
    sub     esp, ecx        ; Local buffer
    mov     edi, esp
    lea     eax, [edx-1]    ; (Rank - 1)
.a: movsb                   ; -> EDI += 1
    add     edi, eax        ; -> EDI += (Rank - 1)
    cmp     edi, ebp        ; Until end of local buffer
    jb      .a
    sub     edi, ecx        ; Back to start of current column
    inc     edi             ; Go to start next column
    dec     edx
    jnz     .a              ; Repeat rank times
    sub     esi, ecx        ; Copy to original storage
    mov     edi, esi        ; -> EDI is Address
    mov     esi, esp        ; -> ESI is local buffer
    rep movsb
    mov     esp, ebp
    pop     ebp edi esi edx ecx
    ret     8
; --------------------------

50+ percent faster without even using an extra buffer.

Matrix     Question     Answer(2)    Faster
-------------------------------------------
16 x 16    3.62 µsec    1.80 µsec    50.1 %
13 x 13    2.67 µsec    1.22 µsec    54.3 %
10 x 10    1.77 µsec    0.77 µsec    56.0 %
 7 x  7    1.02 µsec    0.44 µsec    56.9 %
 4 x  4    0.56 µsec    0.23 µsec    58.9 %

The elements on the main diagonal are never touched. All the other elements are flipped across the main diagonal.

; TransposeSquareMatrix(Address, Rank)
A2: push    ebx ecx edx esi edi ebp
    mov     ebx, [esp+28]   ; Address
    mov     ecx, [esp+32]   ; Rank
    mov     ebp, ecx
    dec     ecx
    jz      .c              ; It's a (1 x 1) matrix
.a: push    ecx             ; (1)
    mov     esi, ebx        ; Column address
    mov     edi, ebx        ; Row address
.b: inc     esi             ; To next element in this row
    add     edi, ebp        ; To next element in this column
    mov     al, [esi]       ; Swap 2 elements
    mov     dl, [edi]
    mov     [edi], al
    mov     [esi], dl
    dec     ecx
    jnz     .b
    add     ebx, ebp        ; To next element on main diagonal
    inc     ebx
    pop     ecx             ; (1)
    dec     ecx
    jnz     .a              ; Continu until (1 x 1) matrix
.c: pop     ebp edi esi edx ecx ebx
    ret     8
; --------------------------


Function for inserting data into database

My suggestion is to simply abandon this piece of code.  I don't know what value that it is adding.  Trying to create some super flexible function that can query any table in any manner is just adding complexity to your application.  How is making this function call easier than just working directly with mysqli in your calling code?

The sending of partial queries and concatenating them to the rest of the query inside this function just serves to obfuscate your code.  Your query is now written in two places rather than one!

Additionally, you have to do things like parse apart the string passed as parameter to figure out how to formulate the query that is to be made. That is added complexity (and potentially fragility) that is just not needed.

I will also offer some thoughts around general coding style that you should considered applying whether or not you use this code.

Avoid using global to make a variable available in function scope.  You are much better off passing the dependency to the code that needs it as a parameter.  This allows you to do things like type hinting the parameters to validate you have the proper dependency before working with it (like a valid mysqli object for example).
Make sure you do not just consider happy path.  For example when working with your DB object, what happens if prepare() fails?  How does your code recover?
You have too much vertical white-space (i.e. empty lines) in your code where there isn't really a need for it.
Some of your lines of code are too long, making your code harder to read.  Consider trying to limit line length to ~80 characters.
Your code indentation (especially around brackets) is inconsistent.  Do this in a consistent fashion so it is clear at a glance where code is nested.
Don't echo out errors to standard output.  Log them!
Don't have unreachable lines of code like you have with your last $stmt->close() call.  Your if-else covers all cases here, so this is totally unnecessary.
You should not use mysqli_real_escape_string() in combination with parametrized prepared statements.  You are going to potentially munge your data by doing this.
A function should only do one thing.  Don't have a function both change data in a database as well as provide HTML-formatted display for error conditions like you have here.  In this case if you have "fatal error", don't die in this function.  Have the function simply report the failure to the calling code (ideally via throwing an Exception) and let the calling code figure out what to do about the error.


Displaying RSS feeds from Google Feed API as HTML list

Looks ok, to be honest. A few minor changes I would make:

I would pull this code out into a function

function ProcessFeedResult(result) {
    if (!result.error) {
        FeedManager.$feedContainer = FeedManager.config.feedContainer;
        for (var i = 0; i < result.feed.entries.length; i++) {
            var entry = result.feed.entries[i];
            $('
').append(
                $(''+entry.title+'').attr(
                {
                    'title': entry.title,
                    'href': entry.link
                }
                ).bind('click',FeedManager.showStory)
            ).appendTo(FeedManager.$feedContainer);
        }
    }
    else{
        FeedManager.handleError(result.error.message);
    }
}

Then I would reverse the condition and return, to reduce the level of indent a bit

function ProcessFeedResult(result) {
    if (result.error) {
        FeedManager.handleError(result.error.message);
        return;
    }

    FeedManager.$feedContainer = FeedManager.config.feedContainer;
    for (var i = 0; i < result.feed.entries.length; i++) {
        var entry = result.feed.entries[i];
        $('
').append(
            $(''+entry.title+'').attr(
            {
                'title': entry.title,
                'href': entry.link
            }
            ).bind('click',FeedManager.showStory)
        ).appendTo(FeedManager.$feedContainer);
    }
}

Further, I would replace the loop with jQuery's $.each()

function ProcessFeedResult(result) {
    if (result.error) {
        FeedManager.handleError(result.error.message);
        return;
    }

    FeedManager.$feedContainer = FeedManager.config.feedContainer;
    $.each(result.feed.entries, function() {
        $('
').append(
            $('' + this.title + '').attr(
            {
                'title': this.title,
                'href': this.link
            }
            ).bind('click',FeedManager.showStory)
        ).appendTo(FeedManager.$feedContainer);
    });
}

You can do any or all of these, I don't think any of it is vastly important. I can read your intent easily enough, it just looks a bit neater to me after refactoring.

Thinking about your later comment a bit, I would also be tempted to append the title, rather than stringing it together.

function ProcessFeedResult(result) {
    if (result.error) {
        FeedManager.handleError(result.error.message);
        return;
    }

    FeedManager.$feedContainer = FeedManager.config.feedContainer;
    $.each(result.feed.entries, function() {
        $('
').append(
            $('').append(this.title).attr(
            {
                'title': this.title,
                'href': this.link
            }
            ).bind('click',FeedManager.showStory)
        ).appendTo(FeedManager.$feedContainer);
    });
}

Otherwise this is the correct approach to generating elements, as far as I know.

As a final step, I would tidy up the braces around the attributes, for consistency

function ProcessFeedResult(result) {
    if (result.error) {
        FeedManager.handleError(result.error.message);
        return;
    }

    FeedManager.$feedContainer = FeedManager.config.feedContainer;
    $.each(result.feed.entries, function() {
        $('
').append(
            $('').append(this.title).attr({
                'title': this.title,
                'href': this.link
            }).bind('click',FeedManager.showStory)
        ).appendTo(FeedManager.$feedContainer);
    });
}

I really don't think you're going to get it any cleaner than that.


Get properties from all children in a recursive SQL structure

There is more than one way to represent a tree and they have different pro's and con's.

In your case you may want to look at modified preorder tree traveral. You can read more about the algorithm here for example.

By giving all nodes a proper left and right value pair you can load an entire subtree in one query for example, which would improve your situation a lot.


Your isAvailable() is wrong.

You check if a number is within the row or col. But you also need to check if it is within the same (3*3) square.

int isAvailable(int puzzle[][9], int row, int col, int num)
{
    int sqCol = col % 3 * 3;
    int sqRow = row % 3 * 3;
    for (int i = 0; i<9; ++i)
    {
        if (puzzle[row][i] == num) return 0;
        if (puzzle[i][col] == num) return 0;

        // You need to add this test.
        if (puzzle[sqRow + (i % 3)][sqCol + (i / 3)] == num) return 0;
    }
    return 1;
}

Rather than having you loop from 0 and then using i+1 why not loop from 1?

for (int i = 0; i<9; ++i)

// I would just do
for (int i = 1; i<=9; ++i)
     Now intuitively use i

Your test for reaching the end of line and end of col is in several places. Rather than test on the call. Just increment the col and handle overflow at the top of the function (in one place). This will greately simplify the whole thing.

int solveSudoku(int puzzle[][9], int row, int col)
{
    if (col == 9) {
        col = 0;
        row++;
    }
    if (row == 9) {
        return 1;
    }

    if (puzzle[row][col] != 0) {
        return solveSudoku(puzzle, row, col + 1);
    }

    for (int i = 1; i <= 9; ++i)
    {
        if (isAvailable(puzzle, row, col, i))
        {
            puzzle[row][col] = i;
            if (solveSudoku(puzzle, row, col + 1))
                return 1;
            }
        }
    }
    puzzle[row][col] = 0;
    return 0;
}


Python and the power of unpacking may help you in this one,

As it is unclear how your Class is used, I will give an example of how to initialize the dictionary with unpacking. This will work on any iterable.

True to it's name, what this does is pack all the arguments that this method call receives into one single variable, a tuple called *args. The same principle applies to **kwargs too, except that in this case it applies to keyword arguments. This most of the time corresponds to dictionaries

An example on how to use **kwargs to initialise your dictionary class

class DummyUpdater(object):
    def __init__(self, iterable=(), **kwargs):
        self.__dict__.update(iterable, **kwargs)

class Passenger(DummyUpdater):
    def __init__(self, iterable=(), **kwargs):
       super().__init__(iterable, **kwargs)

# See the power of unpacking!
# We can create a class like this just with variables
d = DummyUpdater(first_name="abc", last_name='sgkf', middle_name='something else', title='ook iets', maturity='', doc_num='4', doc_type='1900')

# Or with a dictionary
d2 = Passenger({'first_name' : 'abc', 'last_name' : 'def'}) # etc..

EDIT

I am unsure if this is in scope or not, since this question doesn't address this at all, but since @Peilonrayz attended me to the usage of __slots__ I learned something myself and am willing to share this with everyone who is interested.

Secondly setting up a class this way, will imrprove memory usage a lot!

class DummyUpdater(object):
    __slots__ = ['first_name', 'last_name']
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

class Passenger(DummyUpdater):
    __slots__ = ['first_name', 'last_name']
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

# SLOTS MAGIC
# HOWTO init from variables
p = Passenger(first_name='abc', last_name='def')
print(p.first_name) # prints abs
print(p.last_name)  # prints def

# HOWTO init from a dict, notice how I unpack the dictionary to pass all the variables
p2 = Passenger(**{'first_name':'abc', 'last_name':'def'})
print(p2.first_name) # prints abc
print(p2.last_name)  # prints def


Spawning child processes and event-listening

First of all, I think spawning a child process just to scrape for links is overkill. If you're scraping links from multiple online pages, the bottleneck isn't the processing speed but your network latency. Once you grab the page contents, scraping a page is a breeze. A single node process written asynchronously can do this easily.

Now if you really need to spawn that child process, then I might suggest you use Promises, arrow functions and the latest version of node to make this code a bit more compact. Use template strings to construct strings instead of concatenation. Don't forget to define var/let/const.

function scrapeLinks(location) {

  return new Promise((resolve, reject) => {

    var processData = "";
    var errors = "";
    var command = `casperLinkScript.js ${location}`;
    var linkScrapeChild = child_process.spawn(casperjsPath, command);

    linkScrapeChild.stdout.on('data', (data) => processData += data.toString());
    linkScrapeChild.stderr.on('data', (err) => errors += err.toString());
    linkScrapeChild.on("error", (err) => errors = err.toString());
    linkScrapeChild.on('close', function onScrapeProcessExit(code) {

      var uniqueLinks = [...new Set(filterLinks(convertToArray(processData)))];

      if (!uniqueLinks.length) errors += `No valid listings found for ${location}`;

      if (errors)
        reject({ code, errors });
      else
        resolve({ code, uniqueLinks });
    });
  });
}

// Usage
scrapeLinks('http://yahoo.com').then((result) => {
  // result.code
  // result.uniqueLinks
}, (result) => {
  // result.code
  // result.errors
});


Python tool to assemble CodeReview posts from source files

PEP 8

I would review PEP 8. Some of your style choices are not considered best practice by the Python community. Some quick observations:

Constants are given CAPS_WITH_UNDERSCORES. Not function/method parameters. PATH should be path for instance.
There is a space between the binary operators (there are, however, some exceptions: see Other Recommendations). So, for instance: indentation=4 should be indentation = 4.
Instead of if not (args.out==None):, You should do if args.out is not None: (See Programming Recommendations)
I would advise making a main function. Yes if __name__ == '__main__': is a start but I would recommend having a main function (see this answer, in particular the section "An Even Better Way"):

--

def main():
    parser=argparse.ArgumentParser(...)
    ...

if __name__ == '__main__':
    main()


Canonicalizing a large set of addresses using many regex substitutions

Nested loops can be problematic, but you can build regex which can be applied once instead of running foreach

my %replace = (
  str => { re => '\bstr\b', output => "street" },
  rd  => { re => '\brd\b', output => "road" },
);
my ($reCombined) = map qr/($_)/, join "|", map $_->{re}, values %replace;

and later inside while loop,

# my $string = "Foo str bar rd foo";
$string =~ s/$reCombined/$replace{$1}{output}/g;


You're not using pseudo-private properties by way of trapping vars inside the constructor. Thus, there is no incentive to putting the methods on the constructor. It only increases your memory usage because the functions are created per instance and not shared across instances. Suggesting you move them out to the prototype instead.

function PublicGame(){...}
GameRoom.prototype.playerExits = function(){...};
GameRoom.prototype.playerDisconnects = function(){...};
// and so on

this.killGame = function() {
    delete Games[this._id];
};

Make sure you actually destroy the game properly, and not just remove its reference from the Games object. Make sure no handlers are referenced, no sockets running etc. Otherwise, the GC will never pick them up.

function PublicGame (players) {

  this.players = players;

  this.playerExits = function(playerToRemove) {

    this.players.splice(this.players.indexOf(playerToRemove),1);

In JS, we usually assume stuff because of the lack of type information and rely on the engine throwing an error when something is executed with the wrong data.

However, in this case, you're assuming players is an array but never check if it really is during instance creation. The problem will come in later when you start doing array operations. In this case, splice will throw, but only later when a player exits. Then you scratch heads, lose hair and learn that your game has been running with broken data.

Guard players. Make sure it's an array and throw early before your code starts to churn with potentially broken data.

this.selectJudges = function() {
    this.judge = this.players.pop();
    this.players = this.players.unshift(this.judge);
};

You don't really need to pop off the last player to be the judge. Just put the judge in the beginning of the array to begin with and just pick him out using:

this.judge = this.players[0];

this._id = id_counter++;

Wondering if a counter would be a good game ID. What if you start to persist games across app restarts? Or run multiple instances of the game in parallel? They'll all start with 0 and numbers will collide. I suggest you use something like a GUID. They're usually unique and chances of collision are rare. Here's one from StackOverflow.


Finding Possible Strings from Series of Numbers

A string implements IEnumerable<char> and has an indexer, so you can iterate it as an array.

You can therefore simplify this:

string[][] StringMapping = new string[number.Length][];
            int LengthIndex = 0;

            foreach (char c in number)
            {
                switch (c)
                {
                    case '2':
                        StringMapping[LengthIndex] = new string[] {"a", "b", "c"};
                 ...

without any other changes to:

string[] StringMapping = new string[number.Length];
            int LengthIndex = 0;

            foreach (char c in number)
            {
                switch (c)
                {
                    case '2':
                        StringMapping[LengthIndex] = "abc";

and your code will work fine.

You could though create a separate method for the mapping as:

private static string GetPattern(char number)
{
  switch (number)
  {
    case '2': return "abc";
    case '3': return "def";
    case '4': return "ghi";
    case '5': return "jkl";
    case '6': return "mno";
    case '7': return "pqrs";
    case '8': return "tuv";
    case '9': return "wxyz";
    default: throw new InvalidOperationException();
  }
}

So your StringMapping could be initialized as:

string[] stringMapping = number.Select(n => GetPattern(n)).ToArray();

Some would claim that a Dictionary<char, string> would be better instead of the switch statement. In a localized scenario for instance, where you would load the mapping dynamically that would be the solution.

Notice the naming: stringMapping (camelCase) for class fields and local variables instead of StringMapping (PascalCase) that is used for properties and method names.

I find SizeArray unnecessary and waste of memory:

  int[] SizeArray = new int[StringMapping.Length];

The only place you are using it is here:

      if (counterArray[incIndex] + 1 < SizeArray[incIndex])

which could be replaces with:

if (counterArray[incIndex] + 1 < stringMapping[incIndex].Length)

  for (int countdown = totalCombinationCount; countdown > 0; countdown--)

There is nothing wrong with iterating backward if the situation demands it, but at least I have to look an extra time, when I see a backward loop. Here there is no reason for the above backward iteration as you only use it to count combinations, the countdown index isn't used to anything in the loop, so it could run forward without any damage:

for (int countdown = 0; countdown < totalCombinationCount; countdown++)

Your algorithm works fine, but the overall impression is that it is more complex than it has to be, and due to the double nested loops it is not very efficient.

FYI: below are some other approaches (they all use the GetPattern() method shown above):

1) An iterative version that uses a list to cache all the combinations while creating them:

void LetterCombinationsIter(string numbers)
{
  IEnumerable<string> CreateCombinations()
  {
    List<string> combs = new List<string> { "" };

    for (int i = 0; i < numbers.Length; i++)
    {
      List<string> temp = new List<string>();
      string chars = GetPattern(numbers[i]);

      foreach (string comb in combs)
      {
        foreach (char ch in chars)
        {
          temp.Add(comb + ch);
        }
      }

      combs = temp;
    }

    return combs;
  }

  Console.WriteLine(string.Join(Environment.NewLine, CreateCombinations()));
}

2) A recursive version which is often the intuitive choice for this kind of problems:

void LetterCombinationsRec(string numbers)
{
  char[] buffer = new char[numbers.Length];

  IEnumerable<string> HandleIndex(int index)
  {
    if (index >= numbers.Length)
    {
      yield return new string(buffer);
    }
    else
    {
      foreach (char ch in GetPattern(numbers[index]))
      {
        buffer[index] = ch;
        foreach (string comb in HandleIndex(index + 1))
        {
          yield return comb;
        }
      }
    }
  }

  Console.WriteLine(string.Join(Environment.NewLine, HandleIndex(0)));
}

3) Finally a version using Linq that solves the problem in a few lines of code:

void LetterCombinationsLinq(string numbers)
{
  IEnumerable<string> CreateCombinations()
  {
    return numbers.Aggregate(new[] { "" }.AsEnumerable(), (combs, n) =>
    {
      string chars = GetPattern(n);
      return combs.SelectMany(pre => chars.Select(ch => pre + ch));
    });
  }

  Console.WriteLine(string.Join(Environment.NewLine, CreateCombinations()));
}


Instead of this:

    var isInbox  = $(this).parent().is(".icon-inbox") ? true : false;

Since .is(...) is boolean, you can use its returned value directly without the ternary operator:

    var isInbox  = $(this).parent().is(".icon-inbox");

This else is pointless, just delete it:

    } else { }

The indentation is off in the else block, and the formatting doesn't follow common conventions:

    else if(rgx.test(title)){
        title = title.replace(rgx, "[" + txt + "] ");
    }
        else {title = "[" + txt + "] " + title;}

It would be better to write this code like this:

    else if(rgx.test(title)){
        title = title.replace(rgx, "[" + txt + "] ");
    } else {
        title = "[" + txt + "] " + title;
    }

In this code:

var rgx = (isInbox ? /\[\d+\]/ : /\[\+\d+\]/);
if (title.indexOf("•") > -1) {
    rgx = isInbox ? /^(\• )\d+/ : /^(\[)+\d+/;
    title = title.replace(rgx, "$1" + txt);
}
// ...

It's misleading that rgx is first assigned to something,
then it's reassigned to something else inside the if branch.
This makes the reader look suspiciously at the code after the if statement to see if rgx is used again for something.

Looking at the code, rgx is not used again.
Which means,
you're just reusing the variable inside the if branch.
But it's not a good practice to reuse a variable for more than one purpose.
It would be better to create a new variable inside the if branch,
for example:

var rgx = (isInbox ? /\[\d+\]/ : /\[\+\d+\]/);
if (title.indexOf("•") > -1) {
    var rgx2 = isInbox ? /^(\• )\d+/ : /^(\[)+\d+/;
    title = title.replace(rgx2, "$1" + txt);
}


If you want to capture part of a pattern,
you can use preg_match, and surround the pattern you want to capture in (...),
like this:

$live_site_image = "http://example.net/wp-content/themes/example/images/dog-in-park.jpg";
preg_match('/images\/([^-]+)-/', $live_site_image, $matches);
// $matches[0] will be "dog"

$matches will get filled with the content matched within each (...) in the pattern. In this case there will be one match.
The pattern I used is "images/" followed by 1 or more non-dash characters followed by a dash. I only capture the part that you want.

This is just one way to extract "dog" from your input string,
there may be a better pattern more suitable for your purpose,
depending largely on the other possible urls and parts to extract.


There is this thing in Python called unpacking.

The idea being that you can assign at once in several variables all the values contained in a single sequence:

>>> example = (1, 2, 3)
>>> a, b, c = example
>>> print(a, b, c)
1 2 3

In fact, this mechanism works with any iterable, including strings. What's even better is that this syntax got extended in Python 3 to support assigning the remaining of the items into a single variable:

>>> a, *b, c = range(5)
>>> print(a, c)
0 4
>>> print(b)
[1, 2, 3]

Now, let's make good use of it:

def translate_to_piglatin(word):
    vowels = 'aeiou'
    first_letter, *remaining_letters = word.lower()

    if first_letter in vowels:
        return word + 'yay'
    else:
        return ''.join(remaining_letters) + first_letter + 'ay'

Here I removed the need for first_letter, *inner_part, last_letter = word.lower() because I assumed that word was not ill-formed. Since you check for isalpha in your main, you don't really need to do so in this function.

An other improvement would be to define vowel as a constant outside of this function.

Converting back can also easily make use of unpacking:

def translate_to_english(word):
    if word.endswith('yay'):
        return word[:-3]
    else:
        *remaining_letters, last_letter, a, y = word
        return last_letter + ''.join(remaining_letters)

In this case:

I used a condition to enter the if rather than setting a boolean before;
I used the slice syntax to extract out the last 3 characters directly.

In both cases I returned from within the if to simplify the logic and the variable management. Each branch needing its own kind of data structure to work with.

The last thing unpacking can help you with is the choice of language/transformation function. If you define, for each input letter, the name of the language and the associated transformation function in a tuple, you can extract them out easily:

CONVERSION_INFOS = {
    'e': ('english', translate_to_english),
    'p': ('pig latin', translate_to_piglatin),
}

def main():
    to_piglatin = input("Do you want to translate something to piglatin[P], or to english[E]: ").lower()

    while to_piglatin not in CONVERSION_INFOS:
        to_piglatin = input("[P/E]").lower()

    lang, translate = CONVERSION_INFOS[to_piglatin]

    sentence = input("Enter a sentence to translate it into {}: ".format(lang))

    if not sentence.isalpha():
        print("Invalid input, please do not use numbers or punctuation marks")
        sleep(1)
        main()

    translated_sentence = ' '.join(translate(word) for word in sentence.split())

    print(translated_sentence)
    input()
    return True

Note the use of lower on the first two inputs so your while loop can break if the user input 'E' or 'P'.

I also merged some lines together to remove the intermediate variables you only use once and reduce the burden of understanding your code for the reader.

Lastly, you can improve the workflow of your program by making a correct use of return values. You don't need to return something at the end of a function in Python (meaning return True in main is unneccessary) when there is no associated meaning. However, we can make use of it:

We return True if we correctly translated a sentence;
We return False if we couldn't.

def main():
    to_piglatin = input("Do you want to translate something to piglatin[P], or to english[E]: ").lower()

    while to_piglatin not in CONVERSION_INFOS:
        to_piglatin = input("[P/E]").lower()

    lang, translate = CONVERSION_INFOS[to_piglatin]

    sentence = input("Enter a sentence to translate it into {}: ".format(lang))

    if not sentence.isalpha():
        print("Invalid input, please do not use numbers or punctuation marks")
        return False

    translated_sentence = ' '.join(translate(word) for word in sentence.split())

    print(translated_sentence)
    return True

This let you handle retries outside of the function:

while not main():
    pass  # or time.sleep(1) like you did, but it feels a bit unresponsive

You may also want to change the name of the function because it doesn't convey much meaning when calling it like that.


Use if/else/elif conditionals to write a basic Rock Paper Scissors game

Here are some suggestions:

We have three if statements that end in "Tie". We could take all three conditions at once ((player1 == 'scissors' and player2 == 'scissors') or ...), or we could notice that we want the two players to have picked the same thing. So immediately we can simplify these three statements:

if (player1 == player2):
    print "Tie"

That's a lot shorter and simpler, and it doesn't depend on what choices are available. This would work just as well in a game with five or fifty options.
There are still six if statements left, for the cases where the two players pick different things. As suggested by Joel in the comments, a dictionary explaining the hierarchy between the different choices might be useful.

beats = {
    'scissors': 'rock',
    'rock': 'paper',
    'paper': 'scissors',
}

Note that I've done it the other way round to Joel: I think 'rock' = beats['scissors'] looks more natural, but I don’t think it makes too much of a difference.

Now we have a very natural way to describe the cases when the players don't pick the same thing:

if (player1 == player2):
    print "Tie"
elif (player1 == beats[player2]):
    print "Player 1 wins."
elif (player2 == beats[player1]):
    print "Player 2 wins."

Where once there were nine if statements, now there are just three, and this can be made to work for any variant on the game. By swapping out beats, we could play Rock-Paper-Scissors-Lizard-Spock, Bear-Hunter-Ninja, Bacon-Lettuce-Tomato, or anything else we wanted.

This is a good idea for programming in general: we've separated the game logic from the specific choices. Keeping them separate makes our program easier to write and to debug.
I like to wrap self-contained blocks of code (like this game logic) into their own functions.

def play_game(player1, player2, beats):
    """Returns the result of the game with player1 vs player2."""
    if (player1 == player2):
        return "Tie"
    elif (player1 == beats[player2]):
        return "Player 1 wins."
    elif (player2 == beats[player1]):
        return "Player 2 wins."

Now the top and bottom matter. This gets the players’s moves. By separating this from the game logic, we can work on this without worrying about whether we've broken the game.

To get the player's move, you've used:

player1 = raw_input("?")
player2 = raw_input("?")

This is the right way to do it, but the "?" is unnecessarily ambiguous. You should be clear what you want. To quote from The Zen of Python:

  Explicit is better than implicit.

So let’s write a full question here, so that it's clear what the choices mean:

player1 = raw_input("What is player 1's move? ")
player2 = raw_input("What is player 2's move? ")

To validate the input, you add an else block at the end of the code:

else:
    print "This is not a valid object selection."

You'd be better off validating the input when you receive it. Right now, the players have no way of telling which of them entered the wrong thing.

Here's one way you might do that:

player1 = raw_input("What is player 1's move? ")

while player1 not in ['rock', 'paper', 'scissors']:
    player1 = raw_input("That is not a valid object selection. Please try again. ")

Here we continue asking until we get something we like. But we can be more helpful. For example, you could tell the player what choices are available (you could even print this before the players make their initial choices).

While we're looking at this, we can use beats.keys() to get the list of possible choices, rather than typing them out every time. Here's an example:

print "The choices are " + str(beats.keys())

player1 = raw_input("What is player 1's move? ")
while player1 not in beats.keys():
    player1 = raw_input("I didn't get that. Please choose from " + str(beats.keys()))

As an additional point, you might want to do some sort of “fuzzy” matching on the input. The program needs to get the string "rock" precisely, but it’s pretty clear what somebody who types "Rock" or "rock\n" means. String methods like lower() and strip() might be useful here.
Finally, consider putting this code inside a special section if __name__ == '__main__'.

Any code in this section only gets used if the file is run directly (e.g., if somebody types $ python rockpaper.py at the command line). On the other hand, if you use import rockpaper in another script, it gets ignored. Right now, anybody who import's this script starts playing rock-paper-scissors (which they may not want).

There's more information on this around the web or on Stack Overflow.

So this is the sort of thing we might be left with:

def play_game(player1, player2, beats):
    """Returns the result of the game with player1 vs player2."""
    if (player1 == player2):
        return "Tie"
    elif (player1 == beats[player2]):
        return "Player 1 wins."
    elif (player2 == beats[player1]):
        return "Player 2 wins."

if __name__ == '__main__':
    beats = {
        'scissors': 'rock',
        'rock': 'paper',
        'paper': 'scissors',
    }

    print "The choices are " + str(beats.keys())

    player1 = raw_input("What is player 1's move? ")
    while player1 not in beats.keys():
        player1 = raw_input("I didn't get that. Please choose from " + str(beats.keys()))

    player2 = raw_input("What is player 2's move? ")
    while player2 not in beats.keys():
        player2 = raw_input("I didn't get that. Please choose from " + str(beats.keys()))

    print play_game(player1, player2, beats)

It looks more complicated than a stack of conditionals, but this is a lot more maintainable and portable than before.


Start with replacing common code with function calls.
For example, you can create a method for checking if an entire row has the same text:

bool checkRow(int row)
{
    int col = row*3;
    return button[col].getText().equals(button[col+1].getText())
           && button[col+1].getText().equals(button[col+2].getText());
}

Write similar methods for columns and diagonal. Then you can do something like that:

bool checkWin()
{
    for(int i=0; i<3; i++)
    {
        if(checkRow(i))
            return true;
        if(checkCol(i))
            return true;
    }
    if(checkMajorDiag())
        return true;
    if(checkMinorDiag())
        return true;
    return false;
}

And then your entire if-else chain will be replaced with:

if(checkWin())
    {
        JOptionPane.showMessageDialog(null,"Thank you the winner is" + button[2].getText());
        gameOver();
        return;
    }

The code is now much more readable.

Two major points you'd want to remember:

Duplicate code leads to bugs

Let's say you'd have to change the message printed to the user - when the message appears several times this task is tedious, plus in a real (big and complex) situation there's a good chance you'll forget to change one of the usages. In the new version, there's only one line to change.
Atomic operations are always better

When I reviewed your code, I couldn't tell immediately what each if condition means.

checkRow(0) means "check the first row". checkRow(0) is an atomic operation (atomic in this context means a single operation - a single function call).

button[0].getText().equals(button[1].getText()) && button[1].getText().equals(button[2].getText()) is much less understandable. But the real danger here that if the line was button[0].getText().equals(button[1].getText()) && button[2].getText().equals(button[2].getText()), you probably couldn't tell that one index was changed. Which means that debugging atomic operations is much easier.


RE: how to rewrite to make it more readable

Stop using c[a,d]*r. While I have a soft spot for them your code may be more readable via first, second etc.
Name the predicates of the cond statement. What are they testing for? Use flet or labels.
Perhaps name the setf blocks to make it more clear what they are doing.
Perhaps split the setf blocks into separate setf lines. I had to check the hyperspec to verify that in fact each one was evaluated sequentially. It would be clearer if they were explicitly sequential.

To summarize:

improve naming
make things explicit

Re: performance

Without having performance benchmarks I cannot tell how the above changes would change the performance of the code. I also noticed that you didn't specify a optimize declaration. That could be used to change performance.


Credit card validation with reversed array

There's a few glaring issues with your code. Namely your lack of consistent styling. Secondly, you're not doing certain things correctly (iterating over an array rather than imploding it). As this is a code review, I will not be touching on the correctness of the algorithm. Below you'll find two pieces of code - one which I've commented and corrected, and a second which I've removed my comments and old code.

With comments:

<?php

# Grab the numbers array and reverse it.
# Don't just name your variable $array. Name it something meaningful.
$numbers_array = array_reverse( $_POST['array'] );

echo "
 Credit card Before :- ";

# No need to do a for loop, just use implode to make the array into a string
/*for ( $i = 0; $i < sizeof( $array ); $i++ ){
    echo $array[$i];
}*/
echo implode("", $numbers_array);

# Just do one echo instead of two
/*echo "
";*/
echo "

 Credit card after applaying mod 10 Algorthim :- ";

# Start converting the number
# You're doing a sizeof() on every single loop. Just cache it in a $size variable
$size = count($numbers_array);
for ( $i = 0; $i < $size; $i++ ) {
    if ( $i % 2 == 1 ) {
        $numbers_array[$i] += $numbers_array[$i];
        if ( $numbers_array[$i] > 9 ) {
            $numbers_array[$i] -= 9;
        }

        echo "" . $numbers_array[$i] . "";
    } else {
        echo $numbers_array[$i]
    }

    $total += $numbers_array[$i];

    # You're doing the same calculation twice (as above). Why not just echo it up there?
    /*if ( $i % 2 == 1 ){
        echo "" . $numbers_array[$i] . "";
    } else {
        echo $numbers_array[$i];
    }*/
}

echo "
";
if ( $total % 10 == 0 ) {
    echo "This credit card is valid";
} else {
    echo "This credit card is not valid";
}

With no comments:

<?php

# Grab the numbers array and reverse it.
$numbers_array = array_reverse( $_POST['array'] );

echo "
 Credit card Before :- " . implode("", $numbers_array) .
     "

 Credit card after applaying mod 10 Algorthim :- ";

# Start converting the number
$size = count($numbers_array);
for ( $i = 0; $i < $size; $i++ ) {
    if ( $i % 2 == 1 ) {
        $numbers_array[$i] += $numbers_array[$i];
        if ( $numbers_array[$i] > 9 ) {
            $numbers_array[$i] -= 9;
        }

        echo "" . $numbers_array[$i] . "";
    } else {
        echo $numbers_array[$i]
    }

    $total += $numbers_array[$i];
}

if ( $total % 10 == 0 ) {
    echo "
This credit card is valid";
} else {
    echo "
This credit card is not valid";
}


A binary tree , its copy constructor and assignment operator

Assignment operator.

The assignment operator is not 100% exception safe.
You should not modify the current object while you have not yet finished making the copy.

Node& Node::operator=(const Node& other)
{
    value = other.value;

    Node * left_orig = left;
    left = new Node(*other.left);
    delete left_orig;

    // You have modified the left side.
    // If while makeing the copy of the right side
    // it throws an exception (that is caught). Then you
    // have an object that is half one thing (new stuff)
    // and half the other (old stuff on the right).
    Node * right_orig = right;
    right = new Node(*other.right);
    delete right_orig;

    return *this;
}

It should look more like this:

Node& Node::operator=(const Node& other)
{
    Note* newleft  = nullptr;
    Node* newright = nullptr;

    // Do the dangerous stuff in isolation.
    // without changing the chaging the current object.
    try {
        newleft  = new Node(*other.left);
        newright = new Node(*other.right);
    }
    catch(...) {
        // If there was a problem
        // clean up any temporary objects.
        delete newleft;
        delete newright;
        // Then re-throw
        throw;
    }
    // Now perform the exception safe change of state.
    // None of these operations are allowed to throw.
    value = other.value;
    std::swap(left,  newLeft);
    std::swap(right, newRight);

    // Now that the object is in a consistent state.
    // we can delete the old data.
    // Do this last (in other types where the data is not in
    // this can potentially throw).
    delete newLeft;
    delete newRight;

    return *this;
}

Now that looks like a lot of hard work.
There is an easier way to achieve exactly the same affect. You can use the copy and swap idiom.

Node& Node::operator=(Node other)    // Pass by value to generate a copy.
{
    other.swap(*this);               // Swap the state of this and the
                                     // copy we created in `other`
    return *this;
}                                    // destructor of other now
                                     // does the tidy up.

Destructor

Calling delete on a nullptr is valid and does nothing.

Node::~Node()
{
    if (left != nullptr )
    {
        delete left;
    }
    if (right != nullptr)
    {
        delete right;
    }
}

So we can simplify this too.

Node::~Node()
{
    delete left;
    delete right;
}

Why do you need a make_copy?

Node* make_copy(Node* other)
{
    Node * new_node = new Node(*other); // copy constructor invoked
    return new_node;
}

It is quite normal to call the copy constructor directly.

Print statement

You can make the print function a method. Also to make it more versatile you should pass a stream to which you want to print (so it can also print to file). If you want a no argument version just make the stream parameter default to std::cout.

void Node::print(std::iostream& str = std::cin)
{
    std::cout << value << std::endl;
    if (left) {
        left->print(str);
    }
    if (right) {
        right->print(str);
    }
}

This makes it easy to define the output operator for your class.

std::ostream& operator<<(std::ostream& str, Node& data)
{
    data.print(str);
    return *this;
}


Get the next date based on a collection of valid weekdays

You can just step forward one day at a time, until you find a week day that is valid. If you change the second parameter to a params parameter, as svick suggested, the code gets very straight forward:

public static DateTime NextByDayOfWeek(this DateTime target, params DayOfWeek[] validDaysOfWeek) {
  do {
    target = target.AddDays(1);
  } while (!validDaysOfWeek.Contains(target.DayOfWeek));
  return target;
}

You can also make a bitmask out of the valid days, so that you don't have to use the Contains method, which would loop through the collection of valid days for each iteration:

public static DateTime NextByDayOfWeek(this DateTime target, IEnumerable<DayOfWeek> validDaysOfWeek) {
  int valid = 0;
  foreach (DayOfWeek d in validDaysOfWeek) {
    valid |= 1 << (int)d;
  }
  do {
    target = target.AddDays(1);
  } while ((valid & 1 << (int)target.DayOfWeek) == 0);
  return target;
}

I tested both these functions with a range of different values, and they seem to give the correct result in all cases.


Insert rows in the datagridview with a dictionary

Your code is really confusing, not in the least because it is partly in Italian.

It does seem to me that you've coupled your UI and your back-end, and that's something to avoid. Look into developing an n-tier application so your db related code is in a back-end and all you're exposing to the UI is a collection of some sort with data objects.

And the you can bind that collection to your DataGridView, which is a much nicer solution instead of inserting one row at a time. Ideally you'd abandon WinForms, instead look into more modern technologies like WPF and apply MVVM. But if you're stuck with WinForms there are still ways to apply something like MVP.

That is of course a massive leap from the code you have here, so try refactoring one bit at the time.

Construct a class that can contain the results of your db-query, and fill a collection, so you can properly bind your data instead of inserting rows.
Beware of strings like "id_nota_lavaggio" and consider defining them as const so you can easily update them if necessary.
Twice you do Convert.ToInt32(reader["id_nota_lavaggio"]): instead, do it once and store the result in a variable.
I don't know about how well Entity Framework works with MySQL, but there are other ORMs available anyway, so when possible consider abandoning writing ADO and instead work with an ORM.
Comments should tell us why, not what. // Query MySQL is superfluous, and something like // Create a dictionary made by a language key and a description should be told by the code, not the comments (ditto // If there is something in the dictionary).


Be consistent and pythonic in naming functions.

draw_arrow instead of drawArrow

Use comprehensions instead of creating empty list and appending to it in a for loop. It's both faster and easier to read.

def translate(coords, vector):
    # Translates a list of coordinate tuples over a vector tuple
    return tuple(tuple(map(operator.add, c, vector)) for c in coords)

def mirror(coords):
    # Takes a list of coordinate tuples and mirrors it across the first element of
    #    the first tuple
    # Formula: 2 * base - original
    base = coords[0]
    double_base = tuple(map(operator.mul, base, len(base) * (2,) ))
    return tuple(tuple(map(operator.sub, double_base, cord)) for c in coords)

Why have a function that returns a constant value. Why creating a variable when you can just return the value.

def get_arrow_coords():
    return [...]
# or if you worry about mutability - use tuples. They actually faster if you wouldn't try to modify them (creating new ones from old ones) a lot.

arrow_coords = ...

You can also use collections.namedtuple('Size', 'height width') instead of using plain tuples for sizes. This would improve readability a little.

And I'm not sure, but maybe you would benefit from using numpy as it seems that you're doing some matrices work.


Is this a sensible way of using an IoC container?

No. What you are doing is called The Service Locator Antipattern. And it's a bad thing.

The basic rule of thumb: Don't inject the container!.

The IoC container is supposed to be some sort of overseer, wiring your objects together at the bootstrap and configuration level. It isn't an object that's supposed to be injected into other objects, to create objects there.


Doing a qsort function to compare strings, case insensitive

Firstly, thank you for providing a test program.  We could make the test even better, if we make it self-checking:
char const *expected[] = {"Alex", "deacon", "Onus", "zebra"};
for (int i = 0;  i < 4;  ++i) {
    if (strcmp(expected[i], strings[i])) {
        return EXIT_FAILURE;
    }
}

We might consider including some non-alphabetic characters, too ("should "A-team" sort before or after "abacus"?).  And we'll want some tests of equal and almost-equal strings; not just ones that differ in the first character.

There were a few errors and warnings to fix up (I compiled with gcc -std=c17 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds  -Wstrict-prototypes -Wconversion to catch all of these):

We missed a few necessary includes for the comparison function:
#include <ctype.h>
#include <stdint.h>
#include <string.h>

And for the test program:
#include <stdio.h>
#include <stdlib.h>

We're assigning char* pointers using string literals.  Whilst C allows this for historical reasons, it's dangerous, and should be avoided (because assignment through such pointers is UB, and the compiler can't spot that for you).  It's easy to fix that:
const char* strings[4] = {"Onus", "deacon", "Alex", "zebra"};

And one that GCC can't spot:

qsort(strings, 4, 8, scmp);
//               ^^^

We can't assume that a const char* is a particular size on the target platform.  Whilst this value may be correct where you are, it's not true everywhere.  Luckily, C provides the sizeof operator to help:
qsort(strings, 4, sizeof strings[0], scmp);

Looking in detail at the comparison function, it does a lot of extra work to make a copy of each input string (we have to traverse each string up to three times - once to find its length, once to copy and convert case, and once to compare).
Instead of preparing the ground for strcmp(), we could (and should) write a case-insensitive version of strcmp(), so we traverse each string once, and downcase only those characters we actually need for the comparison, as we reach them:
#include <ctype.h>

/* N.B. name not beginning with "str". */
int ci_strcmp(const char *s1, const char *s2)
{
    while (*s1) {
        if (!*s2) {
            /* s1 is longer */
            return 1;
        }
        int c1 = tolower(*s1);
        int c2 = tolower(*s2);
        if (c1 < c2) {
            return -1;
        }
        if (c2 < c1) {
            return 1;
        }
        ++s1;
        ++s2;
    }
    if (*s2) {
            /* s2 is longer */
            return -1;
    }
    /* compare equal */
    return 0;
}

/* Adapter for qsort */
int scmp(const void *p1, const void *p2)
{
    const char *const *sp1 = p1;
    const char *const *sp2 = p2;
    return ci_strcmp(*sp1, *sp2);
}

We can make the body of the comparer more compact (but functionally identical) with a little cleverness:
int ci_strcmp(const char *s1, const char *s2)
{
    for (;;) {
        int c1 = tolower(*s1++);
        int c2 = tolower(*s2++);
        int result = (c1 > c2) - (c1 < c2);
        if (result || !c1) return result;
    }
}

As mentioned in another answer, we need to use unsigned char with tolower():
int ci_strcmp(const unsigned char *s1, const unsigned char *s2)
{
    for (;;) {
        int c1 = tolower(*s1++);
        int c2 = tolower(*s2++);
        int result = (c1 > c2) - (c1 < c2);
        if (result || !c1) return result;
    }
}

/* Adapter for qsort */
int scmp(const void *p1, const void *p2)
{
    const unsigned char *const *sp1 = p1;
    const unsigned char *const *sp2 = p2;
    return ci_strcmp(*sp1, *sp2);
}


Regular Expression in Javascript to test a string of 1s and 0s

Why not simply test the valids?

if((/0110|0100|0010/).test(precode))

Seems more readable to me.


SQL-Server Merge Statement with .NET DataTable

Well done.
I honestly cannot find anything bad to say about your SQL code. Your capitalization of keywords and indentation are consistent. Your query is properly explicit, there is no guessing work that the SQL engine would have to make. You clean up after your operation by dropping your #tempSpecOrderReplication.
The only thing that looked unusual, though not bad, is that you used square brackets in this clause but nowhere else. I would personally prefer if it were consistent thoughout, if I had to maintain it. But it's just a nitpick.
INSERT INTO #tempSpecOrderReplication
([Ord_L_ID], [Ord_ID], [Quantity], [UOM], [Price],
 [Is_Spec_Order], [Item_Number], [Order_Number])
VALUES (...); --These values come from the .NET DataTable


Speeding up Python program that converts DOCX to PDF in Windows

I recently learned how easy it is to incorporate multiprocessing and multithreading into a Python program, and would like to share it with you.
Python's built-in multiprocessing module offers a simple way to add multiprocessing to a program. However, since your program performs a lot of writes, I think it may be better to use the multiprocessing.dummy module instead. This module offers the same API as the multiprocessing module, but is used for multithreading instead of multiprocessing, and thus is better suited to programs that are IO intensive.
First, import the Pool class from the multiprocessing.dummy module:
import Pool from multiprocessing.dummy as ThreadPool
I aliased it as ThreadPool just for added clarity that we are using multithreading and not multiprocessing. Next, take a look at all the for loops in your code. To add multithreading, we will have to change those for loops to call a function on each iteration instead of performing a series of steps:
def create_qr_code(values):
    data = barcode = values["barcode"]
    image = pyqrcode.create(data)
    image.png("codes\\"+f"{barcode}.png", scale=3)

def create_qr_codes():
    for index, values in df.iterrows():
        create_qr_code(values)

def embed_qr_code(image):
    image_name = os.path.basename(image)
    doc = Document()
    doc.add_picture(image)
    last_paragraph = doc.paragraphs[-1]
    last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
    doc.save("docs\\"+f"{image_name}.docx")
    convert("docs\\"+f"{image_name}.docx")

def embed_qr_codes():
    qr_images = glob.glob("codes\\"+"*.png")
    for image in qr_images:
        embed_qr_code(image)

def clean_file_name(path):
    newname = path.replace(".png", "")
    if newname != path:
        os.rename(path, newname)

def clean_file_names():
    paths = (os.path.join(root, filename)
        for root, _, filenames in os.walk("docs\\")
        for filename in filenames)
    for path in paths:
        clean_file_name(path)

Now for the fun part. In each of the functions that use for loops, we will replace the for loops with usages of ThreadPools as context managers. We can then call each ThreadPool's map method to perform the actions using multithreading:
def create_qr_codes():
    rows = (values for _, values in df.iterrows())
    with ThreadPool() as pool:
        pool.map(create_qr_code, rows)

def embed_qr_codes():
    qr_images = glob.glob("codes\\"+"*.png")
    with ThreadPool() as pool:
        pool.map(embed_qr_code, qr_images)

def clean_file_names():
    paths = (os.path.join(root, filename)
        for root, _, filenames in os.walk("docs\\")
        for filename in filenames)
    with ThreadPool() as pool:
        pool.map(clean_file_name, paths)

Note that when instantiating a Pool, you can pass a value to it to specify the number of processes (or in our case, threads) to use. According to the Python docs:

If processes is None then the number returned by os.cpu_count() is used.

Also, don't forget to change these two function calls...
create_qr_code()
embed_qr_code()

...to these:
create_qr_codes()
embed_qr_codes()

This should speed up your program significantly. If not, try using the multiprocessing module instead of multiprocessing.dummy.
Finally, one extra tip. You may want to refactor this function:
def make_folder():
    os.mkdir("codes")
    os.mkdir("docs")

To use the os.makedirs function instead to avoid raising an error if the directories already exist:
def make_folder():
    os.makedirs("codes", exist_ok=True)
    os.makedirs("docs", exist_ok=True)


For overall issues, these jump out:

s[i].is_alphabetic() && i < s.len() can panic, because you access the value before checking the length, it would have to be i < s.len() && s[i].is_alphabetic().
is_alphabetic considers lots of things alphabetic that you probably don't want. If you look at the docs the examples include assert!('京'.is_alphabetic()); which probably isn't what you want.

For Rust itself:

Rather than converting the string to a vector of chars, it's easier to use an iterator. In your case it needs to be an iterator that can .peek so you can stop before consuming the character.
Pattern-matching can make the readability of checking the vowels vs others easier, and it allows you to collapse the logic in your first if. The matches also allow you to cleanly create and define the suffix value earlier, and avoid the usage of the problematic is_alphabetic function.

Here's an updated implementation:

let mut chars = input.chars().peekable();
let mut new_s = String::new();
while let Some(c) = chars.next() {
    let suffix = match c {
        'a' | 'e' | 'i' | 'o' | 'u' => {
            new_s.push(c);
            String::from("-hay")
        }
        'a'...'z' | 'A'...'Z' => {
            format!("-{}ay", c)
        }
        _ => {
            new_s.push(c);
            continue;
        }
    };

    while let Some(&c) = chars.peek() {
        match c {
            'a'...'z' | 'A'...'Z' => {
                chars.next();
                new_s.push(c);
            }
            _ => break,
        }
    }

    new_s += &suffix;
}
println!("{}", new_s);