Cyclomatic Complexity (complexity) I have a program for finding shortest distance/path and I got a correct answer but I am getting an issue i.e., "Function 'shortestPath' has a complexity of 9. Maximum allowed is 6." This is the algorithm:
const graph = {
  start: { A: 5, D: 8 },
  A: { B: 9, C: 3 },
  D: { C: 4, E: 6 },
  C: { B: 5, E: 2 },
  B: { end: 7 },
  E: { end: 4 },
  end: {}
};

function shortestCostNode(costs, processed) {
  return Object.keys(costs).reduce((lowest, node) => {
    if (lowest === null || costs[node] < costs[lowest]) {
      if (!processed.includes(node)) {
        lowest = node;
      }
    }

    return lowest;
  }, null);
}

// this function returns the minimum cost and path to reach end
function shortestPath(graph) {
  // track lowest cost to reach each node
  const costs = Object.assign({ end: Infinity }, graph.start);

  const parents = { end: null };

  for (let child in graph.start) {
    parents[child] = 'start';
  }

  const processed = [];
  let node = shortestCostNode(costs, processed);

  while (node) {
    let cost = costs[node];
    let children = graph[node];

    for (let n in children) {
      if (children.hasOwnProperty(n)) {
        let newCost = cost + children[n];

        if (!costs[n] || costs[n] > newCost) {
          costs[n] = newCost;
          parents[n] = node;
        }
      }
    }

    processed.push(node);
    node = shortestCostNode(costs, processed);
  }

  let optimalPath = ["end"];
  let parent = parents.end;

  while (parent) {
    optimalPath.push(parent);
    parent = parents[parent];
  }

  optimalPath.reverse();

  const result = {
    distance: costs.end,
    path: optimalPath
  };
  return result;
}

How to reduce complexity of Function shortestPath?

Cyclomatic complexity
is a measure of the number of possible paths thorough some code. For example an if statement with one clause eg if (foo) {} has two paths, One if foo is true and one if false. Any point where the code can branch, the branches are counted as part of the cyclomatic complexity.
Unfortunately how the complexity is summed differs so without knowing how the metric was calculated there is no easy way to give an answer. The best you can do is reduce the number of possible branches in the code.
Improving the code
Looking at your code and there is plenty of room to reduce the number of branches.
The function shortestCostNode is not needed as the shortest link in a node has no influence on the final result. The shortest link may well move you to the longest path. Searching for the shortest link is no improvement on picking nodes sequentially.
shortestCostNode is the major source of complexity in your solution, it effectively randomizes your search. Because of this you must track which path you have traveled so you don't end up repeating the same path, this adds a lot of baggage.
If you systematically search all possible paths in order (keeping track of where you have not been) you eliminate the need to track where you have been and can thus remove a lot of code.
Use a stack to search a tree
As the search for the shortest path involves traveling along paths and then backtracking to the nearest untraveled branch a stack is the best way to keep track of your progress.
You start at a node, push all paths and the cost so far to a stack, then pop one path and move along that path to the next node adding the cost as you do. Then do the same for the next node.
When you reach an end node you then check the distance and if it is the shortest so far you save that distance and the path traveled. Then pop the next path step from the stack until all paths have been checked.
A Recursive stack
The simplest (but not the quickest) way to implement a stack is via recursion.
Thus you end up with a function something like
function shortestPath(graph) {
    const result = {distance: Infinity}, endName = "end";
    function followPath(node, totalDist = 0, path = ["start"]) {
        for (const [name, length] of Object.entries(node)) {
            const distance = totalDist + length;
            if (distance < result.distance) {
                if (name === endName) {
                    Object.assign(result, {distance, path: [...path, endName]});
                } else {
                    path.push(name);
                    followPath(graph[name], distance, path);
                    path.pop();
                }
            }
        }
    }
    followPath(graph.start);
    return result;
}

The function has a Cyclomatic complexity of about 5.
Note that the function only follows paths while the distance traveled is less than the shortest path found already found. This means that you may not need to check all paths to the end.
There is also plenty of room for improvement (in terms of complexity and performance), but as you have not defined much about the graphs possible structure there is no point going any further,.


Remove odd valued nodes from linked list The function remove_odd is to remove odd valued nodes (surprise!!) from the linked list head. The code is very long and cryptic but it seems to work.

Please help me reduce the lines of code and are there any cases that I might have missed.

void rem_odd(struct Node** head)
{
    struct Node* curr=*head;
    struct Node* l_even=NULL; //l_even stores the last even number node address
    while(curr!=NULL&&curr->data%2!=0)
    {
        *head=curr->next;
        if(curr->next==NULL)
            return;
        curr=curr->next;
    }
    l_even=curr;
    while(curr!=NULL)
    {
        if(curr->next==NULL)
            return;
        while(curr!=NULL&&curr->next->data%2!=0)
        {

            if (curr->data%2!=0)
            {
                printf("if ");
                if(curr->next==NULL)
                {
                    l_even->next=NULL;
                    return;
                }
                curr=curr->next;
                l_even->next=curr;
                if(curr->next==NULL)
                {
                    l_even->next=NULL;
                    return;
                }
                continue;
            }
            curr=curr->next;
            if(curr->data %2!=0 &&curr->next==NULL)
            {
                l_even->next=NULL;
                return;
            }
        }
        if(curr->next==NULL)
        {
            l_even->next=NULL;
        }
        else
        {
            l_even->next=curr->next;
            l_even=curr->next;
        }
        curr=curr->next;
    }
}

It seems you can simplify this by quite a lot.
I added explanation of the algorithm inside the code,
that way it might be easier to follow:

void rem_odd(struct Node** head)
{
    struct Node* curr = *head;
    struct Node* l_even;

    // iterate until the first even element, or the end
    while (curr != NULL && curr->data % 2 != 0)
    {
        curr = curr->next;
    }

    // the new head is the first even element, or the end
    *head = curr;

    // if no more elements, we're done here
    if (curr == NULL) {
        return;
    }

    // the last even element is the current element, naturally
    l_even = curr;

    // we know the current element is even, and not null, so moving on
    curr = curr->next;

    // iterate until the end
    while (curr != NULL)
    {
        // is the current element even?
        if (curr->data % 2 == 0) {

            // -> yes, it's even, so the last even element should point to it
            l_even->next = curr;

            // ... and this is the new last-even-element now
            l_even = curr;
        }
        curr = curr->next;
    }

    // last even might still point to an odd valued element, so NULL it out
    l_even->next = NULL;
}

Notice that I added spaces around the operators.
For example this is extremely hard to read:

while(curr!=NULL&&curr->data%2!=0)


Can this list comprehension be made more pythonic? Quite a specific question can the below code be made more clearer / pythonic in any way.

Essentially based on the condition of the string x((len(x) / 3) - 1), I use this to extract out parts of the string.

def split_string(x):
    splitted_string = [x[counter*3:(counter*3)+3] for counter in range ((len(x) /3) - 1)]
    return splitted_string

>>> split_string('ABCDEFGHI')
['ABC', 'DEF']

For integer division, use the // operator.  In Python 3, / will do floating-point division.

The task could be more succinctly accomplished using re.findall().

Also, the goal of the function is not obvious.  Pythonic code would include a docstring explaining its purpose.

import re

def split_string(s):
    """
    Splits a string into a list, with each element consisting of
    three characters.  Any incomplete group at the end is discarded,
    and then the last complete group is also discarded.
    """
    return re.findall(r'.{3}', s)[:-1]


Haskell version of HackerRank problem solution "NumberTheory/Restaurant" Link to the challenge

  Given an input of \$T\$ rectangles, each of various dimensions \$l \times b\$, what is the minimum number of identical perfect squares that would cover each rectangle with no overlap or excess?

  Constraints

  \$1 \le T \le 1000\$
  \$1 \le l\$, \$b \le 1000\$

  Sample Input

2
2 2
6 9

  Sample Output

1
6

import System.IO (readLn, getLine)
import Control.Monad (replicateM)

main :: IO ()
main = getNumLoaves >>= getLoafDimensions >>= mapM_ (print . minNumberOfSlices)

getNumLoaves :: IO Int
getNumLoaves = readLn

parseInt :: String -> Int
parseInt = read

tuplefy :: [a] -> (a, a)
tuplefy xs = case xs of [a, b] -> (a, b)
                        _      -> error "each line of input must consist of 2 integer values."

getLoafDimensions :: Int -> IO [(Int, Int)]
getLoafDimensions =
  let rawText         = flip replicateM getLine
      parseDimensions = map $ tuplefy . map parseInt . words
  in fmap parseDimensions . rawText

squares :: [Int]
squares = map (^2) [1..1000]

squareRoot :: Int-> Int
squareRoot squaredNum = floor . sqrt $ fromIntegral squaredNum

minNumberOfSlices :: (Int, Int) -> Int
minNumberOfSlices (l, b) =
  let area                        = l * b
      isPerfectSliceDimension num = area `rem` num + b `rem` squareRoot num + l `rem` squareRoot num == 0
      largestSquare               = last $ filter isPerfectSliceDimension $ take (min l b) squares
  in if l == b
     then 1
     else area `div` largestSquare

getNumLoaves :: IO Int
getNumLoaves = readLn

parseInt :: String -> Int
parseInt = read

Theses functions are useless. It's useful when you're writing the code and it's not done yet, but Haskell can actually deduce the types based on what the other functions parameters type, like getLoafDimensions need an int, so readLn must return an int, otherwise it wouldn't compile

Your tuplefy function can be simplified by removing the case of, which is basically the same as this form of pattern matching

tuplefy :: [a] -> (a, a)
tuplefy [a, b] = (a, b)
tuplefy _      = error "each line of input must consist of 2 integer values."

By the way, the error message is wrong, because that function can accept a list of any type

Both readLn and getLine are defined in the prelude, so you don't need to import them, so you don't need to import System.IO


Implementing a JMS consumer I need a standalone client that consumes messages from the queue every time a message exists. I already have set-up an ActiveMQ queue named hello.world.

ConsumerClient.java

public class ConsumerClient {

    public static void main(String[] args){

        Thread thread = new Thread(new Consumer("tcp://localhost:61616", "hello.world"));
        thread.start();
    }
}

Consumer.java

public class Consumer implements Runnable{

    private String brokerUrl;
    private String queueName;
    private boolean isRunning;

    public Consumer(String brokerUrl, String queueName) {
        this.brokerUrl = brokerUrl;
        this.queueName = queueName;
        isRunning = true;
    }

    @Override
    public void run() {

        while (isRunning) {

            System.out.println("Listening for messages...");

            Connection connection = null;
            MessageConsumer consumer = null;
            Session session = null;

            try {

                //Create a connection factory
                ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);

                //Create a connection
                connection = connectionFactory.createConnection();
                connection.setExceptionListener(new ExceptionListener(){
                    @Override
                    public void onException(JMSException arg0) {
                        System.out.println("JMS Exception occurred...");
                    }
                });

                //Create a session
                session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);

                //Create destination
                Destination destination = session.createQueue(queueName);

                //Create consumer
                consumer = session.createConsumer(destination);

                //Start the connection
                connection.start();

                Message message = consumer.receive();
                if (message instanceof TextMessage) {
                    TextMessage txtMessage = (TextMessage) message;
                    try {
                        //Persist message to database
                        //...some code that persists message to database
                        session.commit();
                    } catch (Exception e) {
                        //Persistence failed
                        session.rollback();
                    }
                }

            } catch (JMSException e) {
                e.printStackTrace();
            } finally {
                if (consumer != null)
                    try {
                        consumer.close();
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }

                if (session != null)
                    try {
                        session.close();
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }

                if (connection != null)
                    try {
                        connection.close();
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
            }
        }
    }
}

I'm not sure if I need to use a MessageListener instead (honestly, I don't know where the MessageListener would fit in my code since if I remove MessageConsumer.receive() and added my own listener, my application hangs since there's no synchronous blocking). We're planning to have at least two of these consumers up just in case one fails.

Is this best practice? We don't use JNDI and I feel that Apache Camel would be too much for a simple process like this.

Should I be creating a deployable .war file instead?

a standalone client that consumes messages from the queue every time a message exists

If you want to process the messages in real time, implementing a message listener is the most practical way -- this way you let ActiveMQ and JMS handle the continuous checking that you're currently doing. As you said, you could do this in a WAR, but a JAR, or thread could accomplish the same task.

If you weren't implementing runnable and coding inside your current while (isRunning) { loop, your current setup would be more appropriate for retrieving one message at a specific time.  Since you are, you're basically telling the JVM to create a connection, create a session, retrieve one message, kill everything, and start over.  This just adds a ton of overhead best left to the API.


Calculating "element-wise" the angles between two lists of vectors Let's say you have two lists of vectors:

v1s = [a, b, c]

v2s = [d, e, f]

I am interested in generating the following result:

angles = [angleBetween(a, d), angleBetween(b, e), angleBetween(c, f)]

Here is my function to do this (it uses vector dot products in order to calculate the angles):

import numpy as np

def findAnglesBetweenTwoVectors(v1s, v2s):
    dot_v1_v2 = np.einsum('ij,ij->i', v1s, v2s)
    dot_v1_v1 = np.einsum('ij,ij->i', v1s, v1s)
    dot_v2_v2 = np.einsum('ij,ij->i', v2s, v2s)

    return np.arccos(dot_v1_v2/(np.sqrt(dot_v1_v1)*np.sqrt(dot_v2_v2)))

I call this function a lot, so optimizing it would be very helpful for me.  Is this possible?

Here's a way of packing the calculation into on call to einsum.

def findAnglesBetweenTwoVectors1(v1s, v2s):
    dot = np.einsum('ijk,ijk->ij',[v1s,v1s,v2s],[v2s,v1s,v2s])
    return np.arccos(dot[0,:]/(np.sqrt(dot[1,:])*np.sqrt(dot[2,:])))

for random vectors of length 10, the speed for this function and yours is basically the same.  But with 10000, (corrected times)

In [62]: timeit findAnglesBetweenTwoVectors0(v1s,v2s)
100 loops, best of 3: 2.26 ms per loop

In [63]: timeit findAnglesBetweenTwoVectors1(v1s,v2s)
100 loops, best of 3: 4.24 ms per loop

Yours is clearly faster.

We could try to figure out why the more complex einsum is slower (assuming the issue is there rather than the indexing in the last line).  But this result is consistent with other einsum testing that I've seen and done.  einsum on simple 2D cases is as fast as np.dot, and in some cases faster.  But in more complex cases (3 or more indexes) it is slower than the equivalent constructed from multiple calls to np.dot or einsum.

I tried tried factoring out the array construction, and got a speed improvement.

In [12]: V1=np.array(v1s)  # shape (3,10000,3)
In [13]: V2=np.array(v2s)
In [22]: timeit findAnglesBetweenTwoVectors2(V1,V2)
100 loops, best of 3: 2.63 ms per loop

I've corrected the times, using v1s.shape==(10000,3)


ACL express middleware implementation I come to see you to help me improve an express middleware that allows you to control access resources by checking the rights of the user.
The following code is supposed to be as generic as possible so that it can easily be added to another project.

But I have doubts both on its genericity and the clarity of its prototype, I let you judge :)

acl.ts

export let config: ACLConfig = {
  userField: 'me',
  roleField: 'roles'
};

export function isAllowed(roles: String[], ...cbs: Function[]) {
  return async function (req, res, next) {
    let allowed = false;
    let user = req[config.userField];
    if (!user) throw new APIError('ACL module cannot find req.{{userField}}', APICodes.ACL_INTERNAL_ERROR);

    let userRoles = user[config.roleField] || '';
    userRoles = userRoles.split(',');

    if (roles && roles.length) {
      for (let role of roles) {
        if (userRoles.indexOf(role) !== -1) return next();
      }
    }

    if (cbs && cbs.length) {
      for (let cb of cbs) {
        if (cb(req) === true) return next();
      }
    }

    throw new APIError('You do not have the required privileges', APICodes.AUTH_ACCESS_FORBIDDEN, HttpStatus.UNAUTHORIZED, true);
  }
}

must be used like this

route('/...').all(verifyToken, isAllowed(['staff, admin'], policies.isMyArticle))

maybe this following prototype is better ?

isAllow(...args: String | Function)
isAllow('staff', policies.isMyArticle, 'staff');

The code you've provided is fairly thin and so there's not to much to pick at here, however, I think your checks on roles and cbs can be simplified using Array.isArray(), because the for of iterator cannot iterate an empty array.

if (roles && roles.length) {
  for (let role of roles) {
    if (userRoles.indexOf(role) !== -1) return next();
  }
}

can be transformed to:

if (Array.isArray(roles)) {
  for (let role of roles) {
    if (userRoles.indexOf(role) !== -1) return next();
  }
}

Although I think these checks would be better moved up and for you to return a 500 Server Error if roles or cbs aren't arrays.

In the same block of code you have indexOf(role) !== -1, which was simplified to .includes(role) in ES6.

The only other thing that comes to mind is the userRoles.split(',') call, because, if userRoles isn't a string, it'll raise an exception. However, that would depend on how malleable your database / validation is.

Additionally, your second suggested prototype has way more confusing usage than your implementation, I would stick with what you've created.


JavaScript switch statement to make an AJAX call I have a button group that looks like this:

The user selects one of the options and they can search for a person based on that criteria.

I wrote a switch statement that populates the URL to make the ajax call to  get the data based on the option selected.

However, the down side of this is that every time an option is added or removed, I have to modify the corresponding JavaScript.

Should I re-factor the code to use data- attributes on the a tags, that contain the URL to use?

Username

Last Name

Student ID

Or is that considered bad mojo?

What I have working:

HTML

Username

Last Name

Student ID

JS

    // All of the list items in the drop down
    var $searchOptions = $('#btGo-dropdown li');
    $searchOptions.click(function (e) {
        var searchBy = '';

        // find all of the child links, which are
        // the options themselves
        var $lis = $searchOptions.find('a');

        // remove the active class, if exists
        $lis.filter('.active').removeClass('active');

        // add the active class to show the criteria selected
        var clickedOptionId = e.target.id;
        $('#' + clickedOptionId).addClass('active');

        // depending on the option selected, populate
        // searchBy with the URL to make the ajax call to
        switch (clickedOptionId) {
            case "btUsername":
                searchBy = 'SearchByUsername';
                break;
            case "btLastName":
                searchBy = 'SearchByLastName';
                break;
            case "btStudentID":
                searchBy = 'SearchByStudentID';
                break;
            default:
        }

        // create an object that abstracts the search data
        var search = {
            url: searchBy,
            data: { criteria: $search.attr('value') }
        };

        // make the call to the controller and get the raw Json
        var itemModels = $.ajax({
            url: search.url,
            type: "GET",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: search.data,
            async: false
        }).responseText;

        // Use knockout.js to bind the information to the page
        viewModel.rebindSearchItems(itemModels);

    });

I don't really think putting the URL in your HTML is a good idea; Separating presentation from functionality and all that...

However, instead of using a switch statement, you should be using an object literal to map the URLs to the clickedOptionId key:

var searchURLs = {
    'btUsername'    : 'SearchByUsername',
    'btLastName'    : 'SearchByLastName',
    'btStudentID'   : 'SearchByStudentID'
};

var search = {
    url: searchURLs[clickedOptionId],
    data: { criteria: $search.attr('value') }
};


Macro for inserting a mini table between heading styles I am using the following macro to insert a mini table of contents between two identical heading styles (e.g. Heading 1). It works fine on small documents, but is very slow on large documents.

Sub MiniTOCFields(HeadingNumber As Long, TOCLevel As Long)
' Add mini TOC fields after all occurrences of a Heading style.
' HeadingNumber defines which heading style to add miniTOCs to (e.g. Heading 1).
' TOCLevel defines to what heading level the TOC shows (e.g. down to Heading 3).

Dim bookmarkNumber As Long
Dim bookmarkRange As Range
Dim insertRange As Range
Dim currentParagraph As Paragraph
Dim paragraphNumber As Long
Dim currentTOC As TableOfContents

bookmarkNumber = 0
paragraphNumber = 0

Set bookmarkRange = ActiveDocument.Paragraphs(1).Range

' Cycle through each paragraph
For Each currentParagraph In ActiveDocument.Paragraphs
     paragraphNumber = paragraphNumber + 1

     ' Check for occurrences of Heading X
     If currentParagraph.Style = "Heading " & HeadingNumber Then

         ' If this is not the first occurrence, create a bookmark between this and the last one
         If bookmarkNumber > 0 Then
             ' Move the end of the bookmark to the end of the next paragraph
             bookmarkRange.End = ActiveDocument.Paragraphs(paragraphNumber - 1).Range.End
             ' Create bookmark
             ActiveDocument.Bookmarks.Add _
                 Name:="TOCHeading" & HeadingNumber & "_" & bookmarkNumber, _
                 Range:=bookmarkRange
         End If

     ' Move the start of the bookmark to the beginning of the next paragraph
     bookmarkRange.Start = ActiveDocument.Paragraphs(paragraphNumber + 1).Range.Start

     ' Add the TOC field
     Set insertRange = currentParagraph.Range
     insertRange.Collapse direction:=wdCollapseEnd
     ' Add the new TOC field
     ActiveDocument.Fields.Add _
         Range:=insertRange, _
         Type:=wdFieldEmpty, _
         Text:=" TOC \h \o """ & HeadingNumber & "-" & TOCLevel & """ \b TOCHeading" & HeadingNumber & "_" & (bookmarkNumber + 1)
     bookmarkNumber = bookmarkNumber + 1
 End If

    ' Check for last paragraph and bookmark
    If paragraphNumber = ActiveDocument.Paragraphs.Count Then
        ' Move the end of the bookmark to the end of this paragraph
        bookmarkRange.End = currentParagraph.Range.End
        ' Create bookmark
        ActiveDocument.Bookmarks.Add _
            Name:="TOCHeading" & HeadingNumber & "_" & bookmarkNumber, _
            Range:=bookmarkRange
        bookmarkNumber = bookmarkNumber + 1
     End If

Next currentParagraph

' Update all TOC fields in document
For Each currentTOC In ActiveDocument.TablesOfContents
     currentTOC.Range.Select
     currentTOC.Update
Next currentTOC

End Sub

Optimization:

You've done a good job of making sure you're not processing more than you have to, but there are a couple of things you can do here to improve performance. Instead of looping through all of the MiniTOCs you've just inserted, updating each one individually. Just update all of the fields in the entire document at once.

Replace This:

' Update all TOC fields in document
For Each currentTOC In ActiveDocument.TablesOfContents
     currentTOC.Range.Select
     currentTOC.Update
Next currentTOC

With This:

ActiveDocument.Fields.Update

It also turns out that there's no reason to  to check every paragraph's style. We can find them all. Below is the uber simplified logic that you would need to implement. Also note that subs/functions should have a verb-noun type name. I changed it in my example.

Private Sub test()
    InsertMiniTOCFields wdStyleHeading1, 3
End Sub

Public Sub InsertMiniTOCFields(headingStyle As WdBuiltinStyle, TOClevel As Long)
    Dim bookmarkRange As Range
    Dim bookmarkNumber As Long
    Dim currentRange As Range
    Dim insertRange As Range
    Dim doc As Document

    Set doc = ActiveDocument
    Set currentRange = doc.Range 'start with the whole doc as the current range

    With currentRange.Find
        .Forward = True         'move forward only
        .Style = headingStyle   'the style given as an argument
        .Execute                'update currentRange to next found instance

        Do While .Found

            ' code to insert bookmarks

            ' Add the TOC field
            Set insertRange = currentRange 'I changed this assignment from currentParagraph to currentRange
            insertRange.Collapse direction:=wdCollapseEnd
            ' Add the new TOC field
            doc.Fields.Add _
                Range:=insertRange, _
                Type:=wdFieldEmpty, _
                Text:=" TOC \h \o """ & HeadingNumber & "-" & TOClevel & """ \b TOCHeading" & HeadingNumber & "_" & (bookmarkNumber + 1)
                bookmarkNumber = bookmarkNumber + 1

            ' update currentRange to next found instance
            .Execute
        Loop
    End With

    'update all newly inserted MiniTOCs
    doc.Fields.Update

End Sub

You can also turn screen updating off to pick up some more performance. You will need to introduce some error handling into your code if you decide to do that though. You'll want to make sure that screen updating is always turned back on when your sub exits; even if it errors. Truthfully, I imagine that this routine should really have an error handler anyway. Here is a pretty good error handling pattern to follow.

Other Notes:

You really shouldn't access the document with ActiveDocument each time. It's much better to store the reference in a variable. This way, you know for a fact that the document you started working on is the one you'll continue to work on.

Dim doc as Document
Set doc = ActiveDocument

Watch your line indentation. Ends should be at the same indentation
level as the If they belong to.
Instead of declaring HeadingNumber as a long in your sub
declaration, you should consider using WdBuiltInStyle.

So instead of this:

Sub MiniTOCFields(HeadingNumber As Long, TOCLevel As Long)
    '......
    ' Check for occurrences of Heading X
     If currentParagraph.Style = "Heading " & HeadingNumber Then

You would have this:

Sub MiniTOCFields(headingStyle As WdBuiltInStyle, TOCLevel As Long)
    '......
    ' Check for occurrences of Heading X
     If currentParagraph.Style = headingStyle Then

You write pretty clean code. I like your variable names. Very concise and easily understandable. You use line continuations judiciously, but it can be a slippery slope. Be careful with that.


Finding possible subset combination from the user input int combiset(int ism,int inarr[],int inpth){
    int r1,r2,r3,r4;
    for(int i=0;i<inpth;i++){
        r1 = inarr[i]+inarr[i+1];
        r2 = r1+inarr[i+2];
        r3 = r2+inarr[i+3];
        r4 = r3+inarr[i+4];

        if(r4==ism){
            printf("%d %d %d %d %d\n",inarr[i],inarr[i+1],inarr[i+2],inarr[i+3],inarr[i+4]);}
        if(r3==ism){
            printf("%d %d %d %d\n",inarr[i],inarr[i+1],inarr[i+2],inarr[i+3]);}
        if(r2==ism){
            printf("%d %d %d\n", inarr[i], inarr[i+1], inarr[i+2]);}
        if(r1==ism){
            printf("%d %d\n", inarr[i], inarr[i+1]);}
    }
}

I am currently designing a function which will calculate and display out the possible combinations of sets from the user input. User will inputs the value of sum that they want to target and the array data such as length and integers inside. For example, if user inputs
array length:10
array data:9 1 5 5 8 9 7 3 1 6
target sum:10

then the result output should look like
9 1
5 5
7 3
3 1 6

Hereby, answer should follow the input array order and answers should be linked, so 1 5 3 1 cannot be an answer.
In my opinion, function which I have designed is too inefficient because user may input the array length as 100 then I have to make r1 until r100 to check whether there is possible combination of sets but with my method, the codes will get tremendously longer. Thus I am thinking of simpler code but I have no idea for it. How can I make my function better to find possible combinations of set?

Avoid repetition
Whenever you are repeating yourself twice or more often, you should immediately find some way to get rid of the repetition. You probably already know how to do this. For example, in this case, just add more for-loops: one to calculate the sum, and another to print all the elements once you have found a set of consecutive elements that sums up to the desired value:
for (int i = 0; i < inpth; i++) {
    int sum = 0;

    for (int j = i; j < inpth && sum < ism; j++) {
        sum += inarr[j];

        if (sum == ism) {
            // Now I know that the sum of element i to j equals ism
            for (int k = i; k <= j; k++) {
                 printf("%d ", inarr[k]);
            }

            printf("\n");
        }
    }
}

Create functions to solve smaller problems
Try to split up your problem in smaller problems, and write functions to solve the smaller problems. This allows you to focus on the smaller problems, and the code usually becomes more readable as well. For example:
/* Print out a single subset */
static void print_subset(int subarr[], int len) {
    for (int i = 0; i < len; i++) {
        printf("%d ", subarr[i]);
    }

    printf("\n");
}

/* Check if summing from the start of the subarray will get us the desired value */
static void check_subset(int ism, int subarr[], int len) {
    int sum = 0;

    for (int i = 0; i < len && sum < ism; i++) {
        sum += subarr[i];

        if (sum == ism) {
            print_subset(subarr, i + 1);
        }
    }
}

/* Check all possible subsets of the input array */
int combiset(int ism, int inarr[], int inpth) {
    for (int i = 0; i < inpth; i++) {
        check_subset(ism, inarr + i, inpth - i);
    }
}

In the above, each function only has a single for-loop, which makes them much easier to reason about than the three nested for-loops in the first example I gave.


Selecting attributes corresponding to the most frequent entries in a junction table I currently am writing a query which retrieves the max amount of rows for a junction table.  I'll use the following example in SQL Fiddle:

  MyTable

┌─────────┬─────────┐
│ a_field │ b_field │
├─────────┼─────────┤
│ a       │ 1       │
│ b       │ 2       │
│ c       │ 3       │
└─────────┴─────────┘

  JunctionTable

┌─────────┬──────────────────┐
│ a_field │ irrelevant_field │
├─────────┼──────────────────┤
│ a       │ z                │
│ a       │ y                │
│ a       │ x                │
│ b       │ z                │
│ b       │ y                │
│ b       │ x                │
│ c       │ z                │
└─────────┴──────────────────┘

Note that in the JunctionTable, 'a' and 'b' are both the most frequent.  I want my query to retrieve '1' and '2', which are the corresponding values to 'a' and 'b' in MyTable.

A naïve version of the query would rely on the fact that the ordering is done on the amount and then limits it on 1 to get the max value:

SELECT b_field
FROM MyTable
WHERE a_field IN (
    SELECT a_field
    FROM JunctionTable
    GROUP BY a_field
    ORDER BY COUNT(a_field) DESC
    LIMIT 1
);

What I want to do, though, is retrieve both 'a' and 'b' without increasing the LIMIT keyword. To achieve this, I can do the following:

SELECT b_field
FROM MyTable
INNER JOIN (
    SELECT a_field, COUNT(a_field) AS amount
    FROM JunctionTable
    GROUP BY a_field
) JC ON JC.a_field = MyTable.a_field
WHERE amount = (
    SELECT MAX(amount)
    FROM (
        SELECT COUNT(a_field) AS amount
        FROM JunctionTable
        GROUP BY a_field
    ) JC2
);

However this screams bad practice to me. Are there any better solutions to this problem?

Observe that this expression is almost repeated:

SELECT a_field, COUNT(a_field) AS amount
    FROM JunctionTable
    GROUP BY a_field

That is an indication that you could use a Common Table Expression.  Given the limited information I have about your situation, I would call it JunctionCount.  I would rename amount, which is ambiguous, to occurrences.

To obtain all junctions that have the maximal number of occurrences, you can use the RANK() window function.

WITH JunctionCount AS (
    SELECT a_field, COUNT(*) AS occurrences
        FROM JunctionTable
        GROUP BY a_field
), MostJunctions AS (
    SELECT a_field, RANK() OVER (ORDER BY occurrences DESC) AS occurrence_rank
        FROM JunctionCount
) SELECT b_field
    FROM MyTable
        INNER JOIN MostJunctions
            ON MyTable.a_field = MostJunctions.a_field
    WHERE MostJunctions.occurrence_rank = 1;


Rod-Cutting Problem using dynamic programming I wrote the following code for solving the Rod-Cutting Problem using dynamic programming:

  Rod Cutting Problem: Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces and also find the size of the pieces to be cut.

import random

prices = {x:random.randrange(x, 2*x) for x in range(1,101)}

def find_optimum_revenue(length, prices, memo={}):
    '''This function finds the maximum possible revenue
       that can be generated by cutting a rod of
       length = length and the prices for each rod of length n
       is stored in prices such that prices[n] finds the price
       of the rod.'''

    if length == 1: # Base Case: You can't cut a rod of length == 1
        return prices[1]

    elif length in memo:
        return memo[length]

    else:
        # The first list will contain all the possible revenues after
        # cutting the rod. We add the list [prices[length]] to add the
        # possibility that we may sell the rod as is and not cut it.

        possible_revenues = [find_optimum_revenue(half, prices, memo) + \
                            find_optimum_revenue
                             (length - half, prices, memo) \
                    for half in range(1, length//2+1)] + [prices[length]]

        memo[length] = max(possible_revenues) # Saving in dictionary for future use
        return memo[length]

get_price = lambda pieces: sum(prices[rod] for rod in pieces)

def find_optimum_cuts(length, prices, memo={}):
    '''This function finds the length of pieces to be cut so
       as to generate the maximum revenue that can be generated
       by cutting a rod of length = length and the prices for
       each rod of length n is stored in prices such that prices[n]
       finds the price of the rod.'''

    if length == 1: # Base Case: You can't cut a rod of length == 1
        return (1,)

    elif length in memo:
        return memo[length]

    else:
        # The first list will contain all the possible revenues after
        # cutting the rod. We add the list [prices[length]] to add the
        # possibility that we may sell the rod as is and not cut it.

        best_cuts = [find_optimum_cuts(half, prices, memo) + \
                    find_optimum_cuts(length - half, prices, memo) \
                    for half in range(1, length//2+1)] + [(length,)]

        memo[length] = max(best_cuts, key=get_price) # Saving in dictionary for future use
        return memo[length]

print(find_optimum_revenue(100, prices))
print(find_optimum_cuts(100, prices))

It works correctly for all the test cases I have tried and is not broken. The first function finds the maximum revenue and the second the pieces to be cut. I am thinking of merging them as it would save time. The prices list contains the prices of different sizes of rods. Is it possible to reduce the time and memory consumption and make the code better and more Pythonic? Also, can you please tell me its time complexity? I believe it to be \$O(n^2)\$ but I am not sure.

I rather like your memo parameter.  It makes for a faster function.  If you are interested, Python 3.2 added the functools.lru_cache function that is used as a decorator and accomplishes the same thing as your memo.

Since possible_revenues is used just to find its max value, it would be more efficient to use a generator expression because the values are generated on demand instead of all being stored in memory.  To do that, simply change [ and ] to ( and ). edit: you would also need to change from ... + ... to itertools.chain(..., ...), importing itertools of course.  When you have an open bracket (any kind, {[(), the logical line continues until it is closed.  Because of that, you don't need the backslash at the end of the line.  I would also suggest that you put the open parenthesis for the second call to find_optimum_revenue() on the same line as the function name.  When I first saw those lines, it looked like you had used a variable and a tuple, but forgot to put a comma between them.

lambda functions are meant to be used where it would be awkward to define a function.  For example, you could use a lambda as an argument to sorted().  It is helpful because you don't need to go through the whole def line just for a one-time-use function.  If you are giving a name to a lambda function, that is a sign that it is not just a simple pass-it-to-another-function deal.  Naming lambdas is actually against PEP 8, the Python style guide.  Instead, use a def line.  If not for the reasons above, using def makes it easier to search for it.  If I want to search for a function  definition, I search for "def function_name(".  It would be hard to remember which functions were defined formally, and which were lambdas.


Raw replacement of space by %20 in Java I tried coding this for practice. Is there a more memory-efficient way to work in place without using more arrays etc (using raw array operations)?

public class SpaceUrlEncoder
{
  // arguments are passed using the text field below this editor
  public static void main(String[] args)
  {
    String unencoded = "Mr John Smith       ";
    int lastCharIdx = 12;
    char[] charr = unencoded.toCharArray();
    for (int i = 12; i >= 0; i--) {
        if (charr[i] == ' ') {
          encodeSpaceAt(i, lastCharIdx, charr);
          lastCharIdx += 2;
        }

    }
    System.out.println("space encoded string: " + new String(charr));
  }

  public static void encodeSpaceAt(int spaceIdx, int lastCharIdx, char[] charr) {
    for (int i = lastCharIdx; i > spaceIdx; i--) {
        charr[i+2] = charr[i];
        charr[i] = ' ';
    }
    charr[spaceIdx] = '%';
    charr[spaceIdx+1] = '2';
    charr[spaceIdx+2] = '0';

  }
}

We should understand what's happening when we do string-related operations in Java. When we concat strings in java, like

 String result = "";
 for(int i=0; i<100; i++){
    result += i+","; // bad, because each string + string creates new string
 }

Strings are immutable, so its bad to += them, instead, StringBuilder is used.
Here's another way to solve this task:

public class ReplaceSpace {

  private static final String REPLACE_SPACE = "%20";
  private static final String SPACE = " ";

  public static void main(String[] args) {
    String input = "Just    some input     string to perform stuff     !";
    System.out.println(replaceString(input));
  }

  private static String replaceString(String input) {
    StringBuilder sb = new StringBuilder();

    int lastPoint = 0;
    int foundIndex;
    int maxIndex = input.length() - 1;
    while ((foundIndex = input.indexOf(SPACE, lastPoint)) != -1 && foundIndex <= maxIndex) {
        sb.append(input.substring(lastPoint, foundIndex - 1));
        sb.append(REPLACE_SPACE);

        lastPoint = foundIndex;
    }

    sb.append(input.substring(lastPoint));

    return sb.toString();
    }

}


Dynamic Dispatch replacement for Generic methods Type erasure is giving me nuts recently. I'm designing a class that performs symbolic differentiation on a math expression represented as a binary expression tree. The question is more on the design part than on the actual code part so I'm only giving out the method that looks awful to me.

public Node derive(final Node currentNode, Node parentNode) {
    Node dxNode = null;

    final Object cDataContext = currentNode.getData();
    if (Number.class.isAssignableFrom(cDataContext.getClass()))
        dxNode = new TreeNode<Double>(0.0);
    else if (AddOperator.class.isAssignableFrom(cDataContext.getClass()))
        dxNode = deriveAddContext((Node<AddOperator>) currentNode);
    else if (MulOperator.class.isAssignableFrom(cDataContext.getClass()))
        dxNode = deriveMulContext((Node<MulOperator>) currentNode);
    else if (SineFunction.class.isAssignableFrom(cDataContext.getClass()))
        dxNode = deriveSineContext((Node<SineFunction>) currentNode);

    if (dxNode != null && parentNode != null)
        dxNode.setParent(parentNode);

    return dxNode;
}

I think it already speaks for itself. I'm having methods with different names which is fine. The awful part at least for me is this huge if statement that I truncated for simplicity. Is there a better way of doing this? I mean I would love to live with dynamic dispatch having the whole derive method consisting of a simple:

Node dxNode = deriveNode(currentNode);
dxNode.setParent(parentNode);
return dxNode;

I guess Java won't give me this luxury so perhaps there is some design pattern that I can utilize here? Just to give you a better understanding of the algorithm I'll show a sample method:

private Node<AddOperator> deriveAddContext(final Node<AddOperator> additionContext) {
    // d/dx [f(x) + g(x)] = d/dx [f(x)] + d/dx [g(x)] => d/dx [f(x)] d/dx [g(x)] +

    // ROOT: ADD
    Node<AddOperator> dRoot = new TreeNode<AddOperator>(new AddOperator());
    // ROOT.LEFT: d/dx [f(x)]
    dRoot.setLeft(derive(additionContext.getLeft(), dRoot));
    // ROOT.RIGHT: d/dx [g(x)]
    dRoot.setRight(derive(additionContext.getRight(), dRoot));
    // RET: d/dx
    return dRoot;
}

So the whole algorithm is recursive on the expression traversing the original expr in an inorder fashion.

A Node has the following structure:

 dataField: <DataType>
 leftChild: Node
 rightChild: Node
 parent: Node

Personally, I would be able to live with your huge if statement if it remains straightforward, is well tested, and hidden in a nice class. I think a parser will often have these types of structures, especially if you are generating it from a grammar using a tool (like ANTLR for example) instead of coding it by hand.

You could slightly improve the huge if statement by factoring out currentNode.getData().getClass() (instead of currentNode.getData()):

final Class<?> dataClass = currentNode.getData().getClass();
if (Number.class.isAssignableFrom(dataClass))
    dxNode = new TreeNode<Double>(0.0);
else if (AddOperator.class.isAssignableFrom(dataClass))
    dxNode = deriveAddContext((Node<AddOperator>) currentNode);
else if (MulOperator.class.isAssignableFrom(dataClass))
    dxNode = deriveMulContext((Node<MulOperator>) currentNode);
else if (SineFunction.class.isAssignableFrom(dataClass))
    dxNode = deriveSineContext((Node<SineFunction>) currentNode);

You could also consider using Java 8 to create an explicit mapping between the class the current node (data) is assignable from and the initialization code for dxNode using lambda expressions. This has the advantage that you should be able to extend the expression types by adding a single line to the map:

public Node deriveAlternative(final Node currentNode, final Node parentNode) {
    Node dxNode = null;

    final Map<Class<?>, Function<Node, Node>> deriveMap = new HashMap<>();
    deriveMap.put(Number.class, n -> new TreeNode<Double>(0.0));
    deriveMap.put(AddOperator.class, n -> deriveAddContext((Node<AddOperator>) n));
    deriveMap.put(MulOperator.class, n -> deriveMulContext((Node<MulOperator>) n));
    deriveMap.put(SineFunction.class, n -> deriveSineContext((Node<SineFunction>) n));

    final Optional<Class<?>> optionalKey = deriveMap.keySet().stream()
            .filter(key -> key.isAssignableFrom(currentNode.getData().getClass()))
            .findFirst();

    if (optionalKey.isPresent()) {
        final Class<?> key = optionalKey.get();
        dxNode = deriveMap.get(key).apply(currentNode);
    }

    if (dxNode != null && parentNode != null)
        dxNode.setParent(parentNode);

    return dxNode;
}


BrainF**k interpreter in C++ This question is the adaptation of this question in C++. (I'm the author of that code as well).

The code:

#include <bits/stdc++.h>

std::string bf_interpreter(std::string code){
    long long int ptr = 0;

    std::vector<int> values = {0};
    long long int length = 1;

    std::vector<int> brackets;

    std::string result = "";

    for(unsigned long long int index = 0; index < code.size(); index++){
        while(length <= ptr){
            length++;
            values.push_back(0);
        }

        char character = code[index];

        switch(character){
            case '>': ptr++; break;
            case '<': ptr--; break;

            case '+': values[ptr] = (values[ptr] + 1) % 256; break;
            case '-': values[ptr] = (values[ptr] - 1) % 256; break;

            case '[':
                brackets.push_back(index);
                break;

            case ']':
                if(values[ptr] == 0)
                    brackets.pop_back();
                else
                    index = brackets[brackets.size() - 1];

                break;

            case '.':
                result += (char)values[ptr];
                break;

            case ',':
                char input; std::cin >> input;
                values[ptr] = (int)input;
                break;
        }
    }

    return result;
}

int main()
{
    std::string s;

    std::cin >> s;

    std::cout << bf_interpreter(s);
}

I'm quite a beginner in C++, so please excuse me if I'm not following any standard conventions.

Bug

The only issue I see is that the data array is never expanded.

As a result any value of ptr that is not zero will cause undefined behavior. What you want to do is give a fixed but reasonable size for the data.

std::size_t const maxDataSize = 10000;

...

   std::vector<int> values;
   values.resize(maxDataSize);

Then make sure when you access the data you mod it to the correct range:

        case '>': ptr = (ptr + 1) % maxDataSize; break;
        case '<': ptr = (ptr - 1) % maxDataSize; break;

Comment

This is not a standard C++ header.

#include <bits/stdc++.h>

What you want is

#include <vector>
#include <string>
#include <iostream>

Comment

The code is non modifiable so the the code parameter should be constant. I would also pass by const reference to prevent a copy or require a move operation to pass the code into the interpretor.

I can see how you would interpret the output as what is printed to the output stream by the interpreter as the result. But is not the whole of memory the actual output?

Two things I would do:

Make . output to the output stream (like , takes from the input stream.
I would give the bf_interpreter() two parameters. The code to execute and the data memory that can be used by the program. The data memory is passed by reference so that any changes can be inspected after the interpreter has finished.
Potentially I would even pass two streams (input/output) as parameters to bf_interpreter(). Though that is a bit more subjective.

Thus my function definition would be this:

 std::string bf_interpreter(std::string const& code,
                            std::vector<int>&  memory,
                            std::istream&      input = std::cin,
                            std::ostream&      output = std::cout
                           );

ReDesign

OK. So given there is a lot more state here than I really want to pass as a function. I would change this a bit and create a "Brain Fuck" class where all the important state is passed to the constructor then you can call interpret on the object.

class BF_Engine
{
         // Add Members here
         void nextStep() {
             // Add interpreter here
         }
    public:
         BF_Engine(std::string const& code,
                   std::vector<int>&  memory,
                   std::istream&      input = std::cin,
                   std::ostream&      output = std::cout
                  );

         void interpret(std::size_t steps = 1)
         {
             while (!finished && steps > 0) {
                 nextStep();
                 --steps;
             }
         }
         void interpretRun()
         {
             while (!finished) {
                 nextStep();
             }
         }
 };


Finding a zero crossing in a matrix I am trying create an algorithm for finding the zero crossing (check that the signs of all the entries around the entry of interest are not the same) in a two dimensional matrix, as part of implementing the Laplacian of Gaussian edge detection filter for a class, but I feel like I'm fighting against Numpy instead of working with it.

import numpy as np

range_inc = lambda start, end: range(start, end+1)

# Find the zero crossing in the l_o_g image
# Done in the most naive way possible
def z_c_test(l_o_g_image):
    print(l_o_g_image)
    z_c_image = np.zeros(l_o_g_image.shape)
    for i in range(1, l_o_g_image.shape[0] - 1):
        for j in range(1, l_o_g_image.shape[1] - 1):
            neg_count = 0
            pos_count = 0
            for a in range_inc(-1, 1):
                for b in range_inc(-1, 1):
                    if a != 0 and b != 0:
                        print("a ", a, " b ", b)
                        if l_o_g_image[i + a, j + b] < 0:
                            neg_count += 1
                            print("neg")
                        elif l_o_g_image[i + a, j + b] > 0:
                            pos_count += 1
                            print("pos")
                        else:
                            print("zero")

            # If all the signs around the pixel are the same
            # and they're not all zero
            # then it's not a zero crossing and an edge.
            # Otherwise, copy it to the edge map.
            z_c = ((neg_count > 0) and (pos_count > 0))

            if z_c:
                print("True for", i, ",", j)
                print("pos ", pos_count, " neg ", neg_count)
                z_c_image[i, j] = 1

    return z_c_image

Here is the test cases it should pass:

test1 = np.array([[0,0,1], [0,0,0], [0,0,0]])
test2 = np.array([[0,0,1], [0,0,0], [0,0,-1]])
test3 = np.array([[0,0,0], [0,0,-1], [0,0,0]])
test4 = np.array([[0,0,0], [0,0,0], [0,0,0]])
true_result = np.array([[0,0,0], [0,1,0], [0,0,0]])
false_result = np.array([[0,0,0], [0,0,0], [0,0,0]])

real_result1 = z_c_test(test1)
real_result2 = z_c_test(test2)
real_result3 = z_c_test(test3)
real_result4 = z_c_test(test4)

assert(np.array_equal(real_result1, false_result))
assert(np.array_equal(real_result2, true_result))
assert(np.array_equal(real_result3, false_result))
assert(np.array_equal(real_result4, false_result))

How do I vectorize checking a property in a matrix range? Is there a quick way of accessing all of the entries adjacent to an entry in a matrix?

Here's concise method to get the coordinates of the zero-crossings that seems to work according to my tests :

def zcr(x, y):
    return x[numpy.diff(numpy.sign(y)) != 0]

Some simple test case :

>>> zcr(numpy.array([0, 1, 2, 3, 4, 5, 6, 7]), [1, 2, 3, -1, -2, 3, 4, -4])
array([2, 4, 6])

This is 2d only, but I believe it is easy to adapt to more dimensions.


jQuery .with() to allow better chaining and flow What are your guys thoughts on the following jQuery plugin?

$.fn.with = function( fn ) {
    // Verify function
    if( jQuery.isFunction( fn ) ) {
        var temp = fn.call(this);

        // Check fn for valid response
        if( temp instanceof jQuery ) {
            return temp;
        }
    }
    return this;
};

I believe this method to very useful as it allows for better chaining, thus increasing flow. Before developing this method, I found myself creating a lot of temporary variables just to preform a conditional test.

Examples would be in cases where .hasClass and .is() are used:

// Example From: http://api.jquery.com/is/

$("ul").click( function( event ) {
    var $target = $(event.target);

    if ( $target.is("li") ) {
        $target.css("background-color", "red");
    }
});

However, using the proposed .with() method, the code can become cleaner:

$("ul").click( function( event ) {
    $(event.target).with(function() {
        if( this.is("li") ) {
            this.css("background-color", "red");
        }
    })
});

Note: If the function processed by .with() returns an instance of jQuery it, instead of the calling instance, will be returned into the chain.

The code

I'm not quite sure of the purpose of this part:

if( temp instanceof jQuery ) {
    return temp;
}

This seems to be related to the idea of chaining methods, but it prevents me from doing something like this:

var width = $('ul').show().with(function() {
    return this.width();
}

Also, when chaining, there is no benefit of only returning the result if it is an instance of jQuery, because if you try to chain methods and you return nothing from with with(), it'll result in "undefined is not a function".

You also check if the fn passed to with() actually is a function. I wouldn't do that, since this will silently ignore a wrong parameter to with(), which is very hard to debug. Instead you can just disable the check, or even better do something like this:

if(jQuery.isFunction(fn)) {
    [...]
} else {
    throw "Parameter passed to `with()` was not a function: " + fn;
}

The idea in general

I have to side with @Esailija here. While there won't be a noticeable performance difference in any modern browser (if you omit the instanceof check), I can't see the benefit of replacing a local variable with an extra level of unnecessary indentation. But that is obviously a purely personal opinion.

Aside from the extra level of indentation, I find the code using with() harder to read, since it removes context from the individual lines. I would prefer something like

$targetEl.css("background-color", "red");

to

this.css("background-color", "red");

any day, because in the former I don't have to scan the surrounding code to see what "this" currently means (which can be hard in JavaScript). Of course this is no concern in a snippet as short as your examples.


Sundaram's sieve in Common Lisp I have this Sundaram's sieve to generate prime numbers up to limit in Common Lisp.

(defun sundaram-sieve (limit)
  (let ((numbers (range 3 (+ limit 1) 2))
        (half (/ limit 2))
        (start 4))
    (dolist (step (range 3 (+ limit 1) 2))
      (dolist (i (range start half step))
        (setf (nth (- i 1) numbers) 0))
      (setq start (+ start (* 2 (+ step 1))))
      (if (> start half)
          (return (cons 2 (remove-if #'zerop numbers)))))))

Here range is defined as:

(defun range (min max step)
   (loop for n from min below max by step
      collect n))

How can i make the code above more functional and idiomatic? The use of setq and setf bothers me, not to mention that it takes 10 seconds to calculate with limit equal 100000, when the equivalent code in Python runs almost instantly.

(let ((numbers (range 3 (+ limit 1) 2))

Above defines a list of numbers. Later you set various numbers to zero. That's not good for a list structure. Use a vector, an one-dimensional array.

(dolist (step (range 3 (+ limit 1) 2))

Creating the list and then iterating over it makes no sense. Use a LOOP statement directly.

  (dolist (i (range start half step))

Creating the list and then iterating over it makes no sense. Use a LOOP statement directly.

Example:

(defun sundaram-sieve (limit)
  (let ((numbers (coerce (cons 2 (range 3 (+ limit 1) 2)) 'vector))
        (half (/ limit 2))
        (start 4))
    (loop for step from 3 upto limit by 2 do
          (loop for i from start below half by step do
                (setf (aref numbers i) 0))
          (incf start (* 2 (1+ step)))
          (when (> start half)
            (return (remove 0 numbers))))))

Runs fast.

CL-USER 36 > (time (sundaram-sieve 100000))
Timing the evaluation of (SUNDARAM-SIEVE 100000)

User time    =        0.007
System time  =        0.000
Elapsed time =        0.004
Allocation   = 1646136 bytes
0 Page faults
#(2 3 5 7 11 13 17 ... 99971 99989 99991)


Reload polyline midpoints into parallel tables I have an Oracle GIS database that has spatial tables. The records in the spatial tables have a geometry column that contains polylines.

I've written a Python 2.7.16 script that calculates the midpoint of the polylines and inserts the midpoint information into parallel tables. The script will be run as part of a nightly scheduled job on a server.

Note: I use the short form FC in the code, which stands for Feature Class. A feature class is an ESRI GIS term that can be thought of as a table with a geometry column.

What the code does:

Loops through a list. Each row in the list has an input FC, a target FC, and an ID field.
For each row in the list:

Truncate the target FC
Populate the target FC with midpoints from the input FC

So yeah, I'm new to Python. How can the code be improved?

import arcpy
conn = "Database Connections\\<YOUR CONNECTION.sde>\\"

#This script only works for polyline feature classes (not polygons or points).
#Caution! The target FCs will get truncated! All records in the target FCs will be deleted.

#       INPUT FC               TARGET FC                     ID FIELD (for both the input FC and the target FC)
lstFC = [\
        ["<OWNER>.<SIDEWALK>", "<OWNER>.S_SIDEWLK_MIDPOINT", "SDW_ID"   ],\
        ["<OWNER>.<SEWER>"   , "<OWNER>.S_SEWER_MIDPOINT"  , "SEWER_ID" ],\
        ["<OWNER>.<ROAD>"    , "<OWNER>.S_ROAD_MIDPOINT"   , "ROAD_ID"  ],\
        ]

def ReloadMidpoints():
    for fc in lstFC:
        inputFC  = conn + (fc)[0]
        targetFC = conn + (fc)[1]
        idField  = (fc)[2]

        arcpy.TruncateTable_management(targetFC)
        print "<" + targetFC + "> has been truncated."

        with arcpy.da.SearchCursor(inputFC, ['SHAPE@', idField]) as s_rows:
            with arcpy.da.InsertCursor(targetFC, ['SHAPE@', idField, "MIDPOINT_X","MIDPOINT_Y"]) as i_rows:
                for row in s_rows:
                    Midpoint = row[0].positionAlongLine(0.50,True).firstPoint
                    rowVals = [(Midpoint.X,Midpoint.Y),s_rows[1],Midpoint.X,Midpoint.Y]
                    i_rows.insertRow(rowVals)

        print "<" + targetFC + "> has been reloaded with midpoints that were generated from <" + (inputFC) + ">."
        print ""

ReloadMidpoints()
print "Complete."

I don't have any experience with arcpy, so possibly some of this may be invalid.
Mostly the code is very good: It's concise; it's clear enough what it does without lot's of documentation, and it has the documentation it needs.
Exactly what makes code "good" depends on how it's going to be used. This looks like a standalone utility you use at your work, so keeing it brief and easy to maintain is probably worth more that thoroughly documenting everything and enforcing type constraints. Not everything below will be applicable to you.
Context:

Use python 3.x if at all possible.
It's good that you've already put most of your code inside a function; now consider using the main method pattern.
The comment about truncating the table is good. You could move it to a confirmation prompt that would be shown to the user at runtime.

Style:

If you have parens of any kind (({[), you don't need to use \ to break your lines.
Your variable names could be more descriptive.
Use snake-case: this_is_a_variable
Be more aggressive about breaking your lines. A reader should rarely, if ever, need to scroll sideways.
Use parens for print statements. print("message") This is required in python 3.
Consider using "string".format() instead of string concatenation. (It make more of a difference in more complicated situations.)
You could save yourself a level of indentation by doing both your DB connections in a single with statement. (but see below)
The warning about truncating the table could be moved to a docstring.
The standard indentation scheme  is 4 spaces per level of indentation, and brackets & parens close on the same level of indentation as the line they were opened on:

lstFC = [
    ["<OWNER>.<SIDEWALK>", "<OWNER>.S_SIDEWLK_MIDPOINT", "SDW_ID"   ],
    ["<OWNER>.<SEWER>"   , "<OWNER>.S_SEWER_MIDPOINT"  , "SEWER_ID" ],
    ["<OWNER>.<ROAD>"    , "<OWNER>.S_ROAD_MIDPOINT"   , "ROAD_ID"  ],
]

Architecture:

It looks like you could make the string literals in lstFC less verbose, by pulling out the common patterns. But that might not be a good idea if those patterns are likely to fail in the future.
Instead of assigning inputFC, targetFC, and idField in three steps, use unpacking to do them all at once.
Alternately, you could save yourself the comment about what's in lstFC by having a class that exposes those as instance properties.
I think it would look better, and be more flexable, to move the for fc in lstFC: loop outside def ReloadMidpoints():, so you'll be calling the function inside the loop.
There's probably a way to do i_rows.insertRows(rows). That way you could first load all the data, then do all the transformations, then write all the data. You'd be making a single large request against the DB, which would likely be faster, and you'd have already succeeded or failed at all of the processing before you ever touched the database. You can even avoid having two connections going on at once.
Speaking of DB safety, consider using a transaction? I don't know how that's done in arcpy.
A lot of database systems support a command called REPLACE, which is like INSERT except it will delete conflicting data before inserting the new rows. If that's an option it might be better than the truncate and rebuild pattern you're using.

To summarize a lot of what I've written:
#!/usr/bin/env python3

import arcpy

DESCRIPTION = """
Transcribe the midpoints of source feature classes
to their respective target feature classes.
This script only works for polyline feature classes (not polygons or points).
CAUTION! The target FCs will get truncated!
         All records in the target FCs will be deleted.
"""

default_connection = "Database Connections\\<YOUR CONNECTION.sde>\\"

default_feature_classes = [
    ("<OWNER>.<SIDEWALK>", "<OWNER>.S_SIDEWLK_MIDPOINT", "SDW_ID"),
    ("<OWNER>.<SEWER>", "<OWNER>.S_SEWER_MIDPOINT", "SEWER_ID"),
    ("<OWNER>.<ROAD>", "<OWNER>.S_ROAD_MIDPOINT", "ROAD_ID"),
]

def main():
    if(_confirm()):
        for (input_FC, target_FC, id_field) in default_feature_classes:
            reload_midpoints(
                default_connection + input_FC,
                default_connection + target_FC,
                id_field
            )
        print(_main_success_message)

def _confirm():
    print(DESCRIPTION)
    input(_confirmation_prompt)
    return True

def midpoint(row):
    return row[0].positionAlongLine(0.50,True).firstPoint

def reload_midpoints(input_connection, target_connection, id_field):
    """Caution!
    The target FCs will get truncated! All records in the target FCs will be deleted."""

    new_rows = []
    with arcpy.da.SearchCursor(input_connection, ['SHAPE@', id_field]) as s_rows:
        new_rows = [
            [(m.X, m.Y), s_rows[1], m.X, m.Y]
            for m in map(midpoint, s_rows)
        ]

    if(new_rows):
        arcpy.TruncateTable_management(target_connection)
        print(_truncation_success_message.format(target_connection))
        with arcpy.da.InsertCursor(
            target_connection,
            ['SHAPE@', id_field, "MIDPOINT_X","MIDPOINT_Y"]
        ) as i_rows:
            i_rows.insertRows(new_rows)
        print(_midpoints_reloaded_message.format(target_connection, input_connection))
    else:
        print(_no_rows_message)

    print("")

_truncation_success_message = "<{0}> has been truncated."
_midpoints_reloaded_message = "<{0}> has been reloaded with midpoints that were generated from <{1}>."
_no_rows_message = "There are no new rows; doing nothing."
_confirmation_prompt = "Press Enter to continue..."
_main_success_message = "Complete."

if __name__ == "__main__":
    main()
```


Stack calculator in Racket I have implemented a stack calculator based on this programming task. I wondered if a more experienced racketeer could give me feedback and tell me if I am missing anything in Racket that would enable the solution to be more elegant.

#lang racket

(define (inc n)
  (+ n 1))

(define (print-value s)
  (begin
    (display s)
    (display " ")))

(define (exec l (stack empty) (opcount 1))
  "executes a stack based program."
  (cond
    [(empty? l) (void)]

    ;; push number onto stack
    [(number? (string->number (first l)))
     (exec (rest l)
           (cons (string->number (first l)) stack)
                 (inc opcount))]

    ;; pop number from stack
    [(equal? (first l) ".")
     (begin
       (print-value (first stack))
       (exec (rest l) (rest stack)
       (inc opcount)))]

    ;; mathmatical operators
    [(equal? (first l) "+")
     (exec (rest l) (cons
                     (+ (first stack) (second stack))
                     (rest (rest stack))) (inc opcount))]
    [(equal? (first l) "-")
     (exec (rest l) (cons
                     (- (first stack) (second stack))
                     (rest (rest stack))) (inc opcount))]
    [(equal? (first l) "*")
     (exec (rest l) (cons
                     (* (first stack) (second stack))
                     (rest (rest stack))) (inc opcount))]
    [(equal? (first l) "/")
     (exec (rest l) (cons
                     (/ (first stack) (second stack))
                     (rest (rest stack))) (inc opcount))]

    ;; duplication operator
    [(equal? (string-downcase (first l)) "dup")
     (exec (rest l)
           (cons (first stack) stack) (inc opcount))]
    [else
     (~a "Error: operation " opcount " invalid")]))

(define program (string-split "64 DUP * ."))

(exec program)

Bug

The - and / operators interpret their operands backwards from the typical RPN order.  That is, I expect "10 7 -" should produce 3, but it actually produces -3.

Recursion

Your code is awfully repetitive, because the handler for each operator has to fetch the operator ((first l)), perform the operation, then make the recursive call ((exec (rest l) … (inc opcount))).  It would be worthwhile to define a helper function that applies the operator to the stack.

(define (apply-op op stack)
  (cond
    [(number? (string->number op))
     (cons (string->number op) stack)]
    [(equal? op ".")
     (begin
       (display (first stack))
       (display " ")
       (rest stack))]
    [(equal? op "+")
     (cons (+ (second stack) (first stack)) (rest (rest stack)))]
    [(equal? op "-")
     (cons (- (second stack) (first stack)) (rest (rest stack)))]
    [(equal? op "*")
     (cons (* (second stack) (first stack)) (rest (rest stack)))]
    [(equal? op "/")
     (cons (/ (second stack) (first stack)) (rest (rest stack)))]
    [(equal? (string-downcase op) "dup")
     (cons (first stack) stack)]
    [else
     (~a "operation '" op "' invalid")]))

Then, the exec function just has to call it and drive the recursion.

(define (exec ops (stack empty) (opcount 1))
  "executes a stack based program."
  (cond
    [(empty? ops) (void)]
    [else
      (let ([next-stack (apply-op (first ops) stack)])
           (if (string? next-stack)
               (~a "Error at operator " opcount ": " next-stack)
               (exec (rest ops) next-stack (+ opcount 1))))]))


Asking 2 values, feet and inches, and it converts them to centimeters I was doing an exercise in PHP, and it works perfectly, no problems. But I think that maybe I coded it so long, and I think it can be shorter than it is now, but I don't know how to make it shorter and that works exactly the same way.

I will explain what this code is doing for you so it's faster if you are going to help (if you want a deeper explanation, you can translate the commented section because that's the wording of the exercise): first of all, I have a PHP file and a html file with a form. The form it's asking for 2 values (feet and inches), for converting them to centimeters. Feet value must be integer, greater than or equal 0. Inches must be integer or decimal, and greater than or equal 0.

<?php
    //Realice un formulario que introduzca dos valores (pies y pulgadas) y los convierta a
    //centímetros. Los pies deben ser un número entero mayor o igual que cero. Las pulgadas
    //son un número entero o decimal mayor o igual que cero. Un pie son doce pulgadas y una
    //pulgada son 2,54 cm.

    $converPC = 30.48;
    $converPlC = 2.54;
    $pies = trim(htmlspecialchars(strip_tags($_REQUEST["pies"]), ENT_QUOTES, "UTF-8"));
    $pulgadas = trim(htmlspecialchars(strip_tags($_REQUEST["pulgadas"]), ENT_QUOTES, "UTF-8"));
    if ( (!empty($pies)) && (!empty($pulgadas)) ) {
        if ( (is_numeric($pies)) && (is_numeric($pulgadas)) ) {
            //Apartado de los pies
            if ( (filter_var($pies, FILTER_VALIDATE_INT)) && ($pies >= 0) ) {
                $resultadoPI = $pies*$converPC;
                print "CONVERSIÓN PIES - CENTÍMETROS
";
                print "$pies pies son $resultadoPI centímetros

";
            } else {
                print "Error en pies
";
                print "Debe introducir un número entero mayor o igual que cero

";
            }
            //Apartado de las pulgadas
            if ($pulgadas >= 0) {
                $resultadoPU = $pulgadas*$converPlC;
                print "CONVERSIÓN PULGADAS - CENTÍMETROS
";
                print "$pulgadas pulgadas son $resultadoPU centímetros";
            } else {
                print "Error en pulgadas
";
                print "Debe introducir un número mayor o igual que cero";
            }
        } else {
            print "Error, ambos valores deben ser numéricos";
        }
    } else {
        print "Para que todo funcione, debe rellenar TODOS los campos del formulario";
    }

?>

This code is pretty compact already so there isn't much room to reduce the size of it. Typically separating the error handling, calculations, and output of content are separated so you may want to look into that for code improvements but that won't make the code any smaller.
Better data sanitation
It's great that you do your best to sanitize user input before you use it. But, there's better ways to go about it. Since
both inputs are expected to be floating point numbers you can use PHP's built in filter_var() with the
FILTER_VALIDATE_FLOAT flag to sanitize the value to a floating point number:
$pies     = filter_var($_REQUEST["pies"], FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
$pulgadas = filter_var($_REQUEST["pulgadas"], FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);

Combine/remove your IF statements
When you see an IF statement followed by another IF statement that's usually a sign that you could combine the two into one as all of them must be true for the following code to be executed:
if ( !empty($pies) && !empty($pulgadas) && (s_numeric($pies) && is_numeric($pulgadas) ) {

The above line can then be shortened thanks to the better sanitation used above. The checks to is_numeric are no longer
needed since filter_var() will return a number or false which will be caught by the empty() checks. So you can now safely remove them:
if ( !empty($pies) && !empty($pulgadas) ) {

You can eliminate your check to see if $pies >= 0 by passing an extra flag to filter_var() to only allow positive numbers and zero.
if ( filter_var($pies, FILTER_VALIDATE_INT) && $pies >= 0 ) {

becomes
if ( filter_var($pies, FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]) ) {

You also forgot to add this check for $pulgadas.
Other notes
Use constants to store values that will remain the same and are unchangeable
Your variables containing the ratios for converting the measurements are better off set as constants than variables since they will remain the same and are unchangeable. (i.e. constant)
$converPC = 30.48;
$converPlC = 2.54;

becomes (notice the use of all capital letters as that is the expected format of constants in PHP)
define('CONVER_PC', 30.48);
define('CONVER_PLC', 2.54);

Omit closing PHP tag
When the closing tag is the last line of a PHP file you can safely omit and it is the standard practice as set forth by
the PSR-2 coding standard for PHP. There are lots of good reasons to do this.
Use echo over print()
print() is an alias of echo but there are minor differences between the two. Although they don't come into play here, it is the PHP convention to use echo for outputting content.
Unnecessary parenthesis
If your IF statements you have parenthesis around each conditional. That is not necessary. You only need to use them when you need to clarify scope. When there's only one condition there is nothing that needs clarification.
Outcome
This code is untested but should give you the idea of what the comments above mean.
define('CONVER_PC', 30.48);
define('CONVER_PLC', 2.54);
$pies     = filter_var($_REQUEST["pies"], FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
$pulgadas = filter_var($_REQUEST["pulgadas"], FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
if ( !empty($pies) && !empty($pulgadas) ) {
    //Apartado de los pies
    if ( filter_var($pies, FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]) ) {
        $resultadoPI = $pies*CONVER_PC;
        echo "CONVERSIÓN PIES - CENTÍMETROS
";
        echo "$pies pies son $resultadoPI centímetros

";
    } else {
        echo "Error en pies
";
        echo "Debe introducir un número entero mayor o igual que cero

";
    }
    //Apartado de las pulgadas
    if ( filter_var($pulgadas, FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]) ) {
        $resultadoPU = $pulgadas*CONVER_PLC;
        echo "CONVERSIÓN PULGADAS - CENTÍMETROS
";
        echo "$pulgadas pulgadas son $resultadoPU centímetros";
    } else {
        echo "Error en pulgadas
";
        echo "Debe introducir un número mayor o igual que cero";
    }
} else {
    print "Para que todo funcione, debe rellenar TODOS los campos del formulario";
}


Find given number by summing up integers from 2 sorted arrays I am working on an algorithm question in which I need to find out pair of number out of 2 sorted arrays which sum up to the given number. I need to print out the indexes of those pairs rather than number itself.

I have written an algorithm which does work but I am wondering is it the best solution or is there any better way to do it (complexity-wise).

    /**
     * Finds and prints all the pairs of indexes from 2 sorted arrays which sum up to the given number
     * @param array1 The first array
     * @param array2 The second array
     * @param sum The number which needs to be constructed by summing integers of both arrays
     */
    private static void findPairs(int[] array1, int[] array2, int sum) {
        if(array1.length == 0 || array2.length == 0)
            return;

        Map<Integer, Integer> firstArrayMap = new HashMap<Integer, Integer>();

        for(int i = 0; i < array1.length; i++) {
            firstArrayMap.put(sum - array1[i], i);
        }

        for(int i = 0; i < array2.length; i++) {
            if(firstArrayMap.containsKey(array2[i]))
                System.out.println("Pair found at index : " + firstArrayMap.get(array2[i]) + " " + i);

        }

    }

Your code reads easily: it loops over the two arrays to find the corresponding pairs.

However, it doesn't take advantage of the fact that both arrays are sorted. You can refer to this Stack Overflow answer by Mark Byers to see how it is possible to do it in linear time and constant storage when both arrays are sorted. Quoting for reference:

  Start with two pointers, one pointing at the smallest element of A, the other pointing to the largest element of B.
  Calculate the sum of the pointed to elements.
  If it is smaller than k increment the pointer into A so that it points to the next largest element.
  If it is larger than k decrement the pointer into B so that it points to the next smallest element.
  If it is exactly k you've found a pair. Move one of the pointers and keep going to find the next pair.

In this version, each pointer will always go forward (for the first array) or backward (for the second array), so there will be at most A.length + B.length moves.

Putting this into code, you would have:

private static void findPairs(int[] array1, int[] array2, int sum) {
    int l = 0, r = array2.length - 1;
    while (l < array1.length && r >= 0) {
        int s = array1[l] + array2[r];
        if (s < sum) {
            l++;
        } else if (s > sum) {
            r--;
        } else {
            System.out.println("Pair found at index : " + l + " " + r);
            l++;
        }
    }
}


Check if a value exists or catch an exception I am parsing a response from server, and in case it contains the fields "chunk_number"(J_ID_CHUNK_NUMBER) and "total_chunk_number"(J_ID_CHUNK_TOTAL), I want to check whether I should request another chunk or not. Not a complicated task. Yet I doubt what would be a better way to implement?

Option 1 - using try catch:

private int getNextChunkNumber(JSONObject jUpdate) {
    try {
        int current;
        int total;
        current = jUpdate.getInt(J_ID_CHUNK_NUMBER);
        total = jUpdate.getInt(J_ID_CHUNK_TOTAL);
        if (current < total) {
            return current + 1;
        }
    }
    catch(JSONException e) {
        // This is an empty exception because it merges with the default result (-1)
    }
    return -1;
}

Option 2 - using the has method:

private int getNextChunkNumber(JSONObject jUpdate) {
    int current;
    if (jUpdate.has(J_ID_CHUNK_NUMBER) &&
        jUpdate.has(J_ID_CHUNK_TOTAL)) {
        current = jUpdate.getInt(J_ID_CHUNK_NUMBER);
        if (current < jUpdate.getInt(J_ID_CHUNK_TOTAL)) {
            return current + 1;
        }
    }
    return -1;
}

I would recommend that you use option 2, especially since you have the ability to avoid the exception (by using the has method).

Exceptions should be used in exceptional circumstances (e.g. You might expect getInt to throw an exception if J_ID_CHUNK_TOTAL exists but does not contain a character which can be parsed to an integer). In which case you would want to wrap the call to that in a catch.

I would also suggest that you do a null check against the jUpdate object before using it.


Creation of playlist to fake-split a full-album video I created this snippet to "split" my full-album videos into its individual songs without the need of actually splitting the video file.

I personally created this snippet because I enjoy reading all musics from a directory in shuffle mode and stumbling upon a full album kinda ruins the point.

#!/usr/bin/python3
# -*- coding: utf-8 -*-

__author__ = 'JeromeJ'
__website__ = 'http://www.olissea.com/'

# Match example for this regex:
#   32. Random song title - 1:33:05
DEFAULT_PATTERN = '^[0-9]+\.\s*(?P<SONG_TITLE>.*?)\s*-\s*(?P<START_TIME>[0-9]+\:[0-9]+(?:\:[0-9]+)?)'

SONG_TITLE = '{ALBUM_TITLE}: {SONG_TITLE}'  # What the song will be titled
ALBUM_TITLE = ''

import pathlib
import re

import pdb

print('M3U8 PLAYLIST MAKER')
print('Please put a .txt file containing the songs\' list next to the album')
print('with the same name as the album file.')
print()
print('The playlist will be saved in current directory.')
print('The links in the playlist are relative, not absolute.')
print()

# TODO: Idea: Allow to drag-and-drop the file on the script to run it.
#   -> Doesn't seem to work (Tried on W7 only so far)
filename = input('Path to album? ')

txt_file = str(pathlib.Path(filename).with_suffix('.txt'))

# Saves the playlist in the current directory with the same name as the album
playlist_file = pathlib.Path(filename).stem + '.m3u8'

pattern = input('Pattern for the songs\' list? (Default: {})\n'.format(DEFAULT_PATTERN)) or DEFAULT_PATTERN
song_title = input('Song title? (Default: {}) '.format(SONG_TITLE)) or SONG_TITLE
album_title = input('Album title? (Default: {}) '.format(ALBUM_TITLE)) or ALBUM_TITLE

playlist_entries = []

with open(txt_file, mode='r', encoding='utf-8') as song_list:
    for i, line in enumerate(song_list):
        r = re.search(pattern, line)

        # pdb.set_trace()

        start_time = r.group('START_TIME').split(':')
        start_time = \
            int(start_time[-1]) \
            + int(start_time[-2])*60 \
            + (int(start_time[-3])*60*60 if len(start_time) > 2 else 0)

        playlist_entries.append(
            """#EXTVLCOPT:start-time={start_time}
#EXTVLCOPT:stop-time={stop_time}
#EXTINF:0, - {album_title}: {song_title}
{filename}""".format(
                start_time=start_time,
                stop_time='{stop_time}',  # To be set by the next iteration
                album_title=album_title,
                song_title=r.group('SONG_TITLE'),
                filename=filename
            )
        )

        if i:
            playlist_entries[i-1] = playlist_entries[i-1].format(stop_time=start_time)

# Up until the end of the file
playlist_entries[-1] = playlist_entries[-1].format(stop_time=0)

with open(playlist_file, 'w', encoding='utf-8') as f:
    f.write('\n\n'.join(playlist_entries))

print()
input('Done. Press Enter to leave.')

Any advice/opinion about how to improve this code in its Python-ness is welcome!

What 'could' be improved?
What is wrong or advised against?

EDIT: As I've been suggested I could/should turn this into a lib. For my excuse this is "just a snippet".

Also I want to keep it as KISS as possible.

Example:
The script turns this:

01. Once Upon a Time - 00:00
02. Start Menu - 01:28
03. Your Best Friend - 02:00

Into this:

#EXTVLCOPT:start-time=0
#EXTVLCOPT:stop-time=88
#EXTINF:0, - Undertale: Once Upon a Time
..\Full albums\Undertale OST.mp4

#EXTVLCOPT:start-time=88
#EXTVLCOPT:stop-time=120
#EXTINF:0, - Undertale: Start Menu
..\Full albums\Undertale OST.mp4

#EXTVLCOPT:start-time=120
#EXTVLCOPT:stop-time=144
#EXTINF:0, - Undertale: Your Best Friend
..\Full albums\Undertale OST.mp4

Instead of using print() you can add a newline character \n at the end of the previous printed string:

print('with the same name as the album file.\n')
print('The playlist will be saved in current directory.')

When you ask for a filename, you don't do any input validation. What if they enter an empty string? What if their path isn't real? I'm not familar with pathlib, and also not sure what you'd want to do. You could create an infinite loop that will only break when the user enters a valid/existing path. Alternatively you could end the program if an invalid path appears. You definitely shouldn't ignore errors or leave it to Python to raise whatever errors it sees fit. You should make explicit choices about what happens.

When you're appending the string to playlist_entries, it's quite hard to read. You would do better to define an ENTRY_TEMPLATE string at the top of the file which you just use and format when appending.

Python truthiness can be very useful, but in this case if i is liable to confuse people. I would suggest either an explicit statement like i != 0 or a comment.

    if i:  # Not the first entry


Reading Large Files in Java getting really slow I am trying to read a large file ~200 MB (~300 million lines of text). I am using a relatively standard way of reading like:

for (int i = 1; i <= numProcs; i++) {
    System.out.println("Parsing " + traceFilePrefix + i + ".prg");
    System.out.println("##########################");

    try {
        String line;
        int instrType;
        String hexAddr;
        ArrayList<Trace> traces = new ArrayList<Trace>();

        int lineNum = 1;

        BufferedReader br = new BufferedReader(new FileReader(traceFilePrefix + numProcs + "/" + traceFilePrefix + i + ".PRG"));
        while ((line = br.readLine()) != null) {
            line = line.toUpperCase();
            // validate line format
            if (line.matches(regexLineFormat)) {
                StringTokenizer tokenizer = new StringTokenizer(line);
                instrType = Integer.parseInt(tokenizer.nextToken());
                hexAddr = tokenizer.nextToken();

                traces.add(new Trace(instrType, hexAddr));
            } else {
                // line is in invalid format
                System.err.println("ERR: line " + lineNum + " is invalid \"" + line + "\"");
            }
            lineNum++;

            if (lineNum % 1000 == 0) System.out.println("line " + lineNum);
        }
        br.close();
        processorsTraces.add(i-1, traces);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

I find that reading slows down at about line 20 million... in face it doesnt seem to progress at all ... how can I improve this? Whats the problem in this simple piece of code?

A latest run seem to run out of heap space ... I guess I cant store data in an arraylist like that?

This is supposed to be a simulator. It first parses trace files containing hexadecimal addresses of memory accesses. Then is supposed to run simulation of these data. This code snipplet only parses and stores the traces in an arraylist.

The issue is almost certainly in the structure of your Trace class, and it's memory efficiency. You should ensure that the instrType and hexAddress are stored as memory efficient structures. The instrType appears to be an int, which is good, but just make sure that it is declared as an int in the Trace class.

The more likely problem is the size of the hexAddress String. You may not realise it but Strings are notorious for 'leaking' memory. In this case, you have a line and you think you are just getting the hexString from it... but in reality, the hexString contains the entire line.... yeah, really. For example, look at the following code:

public class SToken {

    public static void main(String[] args) {
        StringTokenizer tokenizer = new StringTokenizer("99 bottles of beer");
        int instrType = Integer.parseInt(tokenizer.nextToken());
        String hexAddr = tokenizer.nextToken();
        System.out.println(instrType + hexAddr);
    }
}

Now, set a break-point in (I use eclipse) your IDE, and then run it, and you will see that hexAddr contains a char[] array for the entire line, and it has an offset of 3 and a count of 7.

Because of the way that String substring and other constructs work, they can consume huge amounts of memory for short strings... (in theory that memory is shared with other strings though). As a consequence, you are essentially storing the entire file in memory!!!!

At a minimum, you should change your code to:

hexAddr = new String(tokenizer.nextToken().toCharArray());

But even better would be:

long hexAddr = parseHexAddress(tokenizer.nextToken());

EDIT: Request to get help on how to debug the code:

To debug the code, you need to set a break-point in the method. Select the line System.out.println(...); and use the key-board short-cut Ctrl-Shift-B which will toggle a break-point, and you will get the 'dot' marker like the picture below:

Then, with that break-point enabled, you need to debug the program:

Right-click on the 'main' word in the public static void main (String[] ...) and select 'Debug As -> Java Application'

This should prompt you to go to the 'Debug' perspective, and you will have a window with the 'Variables' displayed. One of the variables will be hexAddr and you can expand it to show its contents. Here's a screen-shot:

From the variables section there are a few things of note. At the bottom, the 'value' variable is highlighted, and it's internal value is shown in the area below ( [9, 9,  , b, o, ......, r]

You can see the count and offset variables for hexAddr too. This means that the hexAddr variable stores the char[] array for the entire line, but also stores an offset and count in that array which it uses for managing the subset of the chars that this String instance is interested in


Reducing code for animation of expanding menus I wonder if I can reduce the code to optimize it better?

$(document).ready(function () {
    $('#menu-1, #menu-event-1').hover(function () {
        $('#menu-deco-1').stop().animate({
            right: 0
        }, 'fast');
    }, function () {
        $('#menu-deco-1').stop().animate({
            right: -280
        }, 'fast');
    });
    $('#menu-2, #menu-event-2').hover(function () {
        $('#menu-deco-2').stop().animate({
            right: 0
        }, 'fast');
    }, function () {
        $('#menu-deco-2').stop().animate({
            right: -280
        }, 'fast');
    });
    $('#menu-3, #menu-event-3').hover(function () {
        $('#menu-deco-3').stop().animate({
            right: 0
        }, 'fast');
    }, function () {
        $('#menu-deco-3').stop().animate({
            right: -280
        }, 'fast');
    });
    $('#menu-4, #menu-event-4').hover(function () {
        $('#menu-deco-4').stop().animate({
            right: 0
        }, 'fast');
    }, function () {
        $('#menu-deco-4').stop().animate({
            right: -280
        }, 'fast');
    });
    $('#menu-5, #menu-event-5').hover(function () {
        $('#menu-deco-5').stop().animate({
            right: 0
        }, 'fast');
    }, function () {
        $('#menu-deco-5').stop().animate({
            right: -280
        }, 'fast');
    });
});

@Bludream came quite close, he noticed the code that was copy pasted, turned the common parts into a function, and then he used a loop to execute everything. The error is in doing both animations on the hover event. This should work:

var mouseLeaveAnimation = { right: -280 };
var mouseEnterAnimation = { right: 0 };

for(var i = 1; i < 6; i++) {

  $('#menu-' + i + ', #menu-event-' + i).hover(function() {
    $('#menu-deco-' + i).stop().animate(mouseEnterAnimation, 'fast');
  }, function() {
    $('#menu-deco-' + i).stop().animate(mouseLeaveAnimation, 'fast');
  });
}


Concept for PHP Controlled, Privileged Execution (for a cPanel knockoff on Ubuntu Server) I was thinking of building a F/OSS project as a cPanel for Ubuntu Server, since Ubuntu doesn't have this, and yet making it easy for a hosting company to use this, where users will find it just as intuitive as cPanel.

Trouble is, PHP web pages on Ubuntu run as www-data, and lots of senior PHP guys recommend not running a PHP page as root, and not shelling out and running a Bash script that may have a sticky bit applied on its permissions. They say that's a way to get hacked.

It then dawned on me how to get around this. Make a Bash script daemon in /etc/init.d that watches a named pipe connection, sitting in a loop. The loop will hang, but that's perfectly okay because it will be in the background, and in a sense it means that the script is dormant and not soaking up CPU cycles. That's cool! It's certainly better than a sleep loop, and means the process only wakes up when there's something that needs to be processed. The sleep loop technique, on the other hand, may be checking for PHP communication when there may not be any, and so the sleep loop soaks up unnecessary CPU. That's why I like the pipe-wait-loop strategy.

So, then all the PHP page has to do is do normal file I/O to like /tmp/pipe (my pipe, for instance) and the Bash script daemon in the background will wake up out of dormancy in that loop, and process a command as root. It can look in a database for new things it needs to do, and then do those tasks. When done, it can return values to the database and the PHP page can wait in a jQuery/AJAX loop until it receives a response back.

Because the PHP page doesn't actually compose the root commands it needs to run, and merely writes some records to a database table, and sends a string of "run" to the pipe, it safely passes on a request to the secure daemon in the background.

What do you think of this IPC technique? Good? Bad?

BTW, my demo /usr/sbin/foo command looks like this. Its point is to demonstrate that /tmp/foo-was-here was created by the root user account, triggered by a PHP page. It's just the start of something bigger.

#!/bin/bash

if [ ! -f /tmp/foo ]; then
    mkfifo /tmp/foo
fi

while true; do
    cat /tmp/foo;
    touch '/tmp/foo-was-here';
done

I'd say: go run a gearman daemon as the correct user, and set some gearman workers as priviliged users up with something like supervisord. Both are in the Debian packages, so I assume they'll be in the Ubuntu packages also....

Do set up gearman with a maximum number of tries, or you could encounter a Poison Message problem.